4 Replies Latest reply on Nov 12, 2007 8:13 PM by 807600

    Padding a String using String.split

    807600
      Firstly I'll just state that this is a question from my uni course, as such I would really appreciate an explanation of any code used.

      Essentially I need to take a string in the form of a sentence (for instance):

      *** the character > represents a space ***

      This>is>a>test>string.

      And then give the ability to justify the words so that a given number of spaces pad the string out (for instance):

      Number of characters long the string is to be: 36

      This>>>>>is>>>>>a>>>>test>>>>string.

      Like in the example above, if it is not possible for the number of spaces between the words to be equal, then the "extra space" needs to be added on the left.

      To clarify what I mean:

      Original string length: 22 Characters
      "Justified" string length: 36 Characters
      Number of spaces that need to be added: 14
      Number of words (or tokens): 5
      Number of gaps between words to put spaces in: 4

      So 14 extra spaces divided by 4 gaps means 3.5 spaces added to each gap, so two gaps must have 4 spaces added to them, and two gaps must have 3 spaces added to them. The spaces need to be added in order from left to right.

      Having looked through the API it seems String.split is recommended over String Tokenizer now (I've used String Tokenizer before, although not for anything remotely complicated, but not String Split). Here's as far as I've got before becoming stuck (a bit of the code is partly poached from another thread on these forums):
      .
      .
      .


      justifiedStringLength is a variable for the method
      String[] result = "This is a test string".split("\\s");
           
      ((justifiedStringLength - String.length) / (result.length - 1) = spacesToBeAddedToEachGap)
      
      for (int x=0; x<result.length; x++)
      
      System.out.print(result[x]);
      I figure that I need to somehow work out how to:
      Turn spacesToBeAddedToEachGap into a set (perhaps an array?) of whole numbers.
      And then work out how to concatenate that new string into the final string....

      I'm lost and confused... Am I making this far more complicated than it needs to be?

      Any help would be very much appreciated.
        • 1. Re: Padding a String using String.split
          807600
          int numberOfWords = stringArray.length();
          int numberOfSpaces = numberOfWords -1;
          char delimiter = '>';
          numberOfDelimitersToAddToEverySpace=(int)numberOfCharactersToAdd / numberOfSpaces; 
          numberOfSpacesToAddAnExtraDelimiterTo = (int)numberOfCharactersToAdd%numberOfSpaces;
          //Add the delimiters to the end of the elements of the stringArray, and concatenate the array
          is this the sort of help you're looking for?

          Edited by: redfalconf35 on Nov 12, 2007 2:10 PM
          • 2. Re: Padding a String using String.split
            807600
            Feel a little out of my depth (my depth being about as deep as a small puddle), but I think I can see that what you've done is kind of give me the logic of how to get the integers I need to use to add the delimiters to the end of each element in the array (as you've said at the bottom).

            A few questions about what you've written:

            Should
            numberOfCharactersToAdd%numberOfSpaces
            be:
            numberOfCharactersToAdd / numberOfSpaces
            ?

            Would I use an arrayList to store the string in after I have have used string.split to take the words from it? How exactly would I go about that?

            If so, how would I add the delimiter to the element in the arrayList? With stringArray.set? (Do I add an extra delimiter to take into account the space that was already in the string (before any extra spaces were added)?)

            How would I return the result? Using a loop to return each element? I know with an Array you can use toString to return an array of Strings, but there doesnt seem to be anything similar with arrayList in the API and it's been a long time since I used it. Not quite sure how I can kind of concatenate that and turn it into a string.

            Your answer certainly helped me think in the right direct at the least, thanks :)
            • 3. Re: Padding a String using String.split
              807600
              Do you have the later version of the JDK? ... if so check out printf

              If you do not, simply build your own method:
              public String rpad(String _s, int length) {
                int          _sLength = _s.length();
                StringBuffer sb        = new StringBuffer(_s);
                String       returnVal = _s;
                if ( _sLength > length)
                  returnVal = _s.substring(0, length);
                else
                if (_sLength < length) {
                  for (int idx = 0; idx < length; idx++)
                    sb.append(" ");
                  returnVal = new String(sb);
                }
                return(returnVal);
              }
              BTW ... this part for the String padding part of your question.

              Edited by: abillconsl on Nov 12, 2007 8:08 PM
              • 4. Re: Padding a String using String.split
                807600
                Dagormatix wrote:
                Feel a little out of my depth (my depth being about as deep as a small puddle), but I think I can see that what you've done is kind of give me the logic of how to get the integers I need to use to add the delimiters to the end of each element in the array (as you've said at the bottom).

                A few questions about what you've written:

                Should
                numberOfCharactersToAdd%numberOfSpaces
                be:
                numberOfCharactersToAdd / numberOfSpaces
                ?
                the % means modulus(remainder):

                www.cafeaulait.org/course/week2/15.html


                Would I use an arrayList to store the string in after I have have used string.split to take the words from it? How exactly would I go about that?
                typically you use a string array to store the strings when using string.split, it would look something like this:
                String[] splitStrings = origString.split(">");
                http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)

                If so, how would I add the delimiter to the element in the arrayList? With stringArray.set? (Do I add an extra delimiter to take into account the space that was already in the string (before any extra spaces were added)?)
                the delimiter (">") will be removed from the strings when split() is used. in order to add the new delimiters, a simple way is to do this:
                stringArray[currentIndex] = stringArray[currentIndex] + ">";
                How would I return the result? Using a loop to return each element? I know with an Array you can use toString to return an array of Strings, but there doesnt seem to be anything similar with arrayList in the API and it's been a long time since I used it. Not quite sure how I can kind of concatenate that and turn it into a string.
                this will be similar to the answer above:
                concatenatedString = concatenatedString + stringArray[currentIndex];
                >
                Your answer certainly helped me think in the right direct at the least, thanks :)
                my answers to these questions may be ambiguous at times... don't hesitate to ask me to clarify any of the points. Otherwise, good luck