tags:

views:

207

answers:

8

If I have an ArrayList that has lines of data that could look like:

bob,      jones,    123-333-1111
    james, lee,  234-333-2222

How do I delete the extra whitespace and get the same data back? I thought you could maybe spit the string by "," and then use trim(), but I didn't know what the syntax of that would be or how to implement that, assuming that is an ok way to do it because I'd want to put each field in an array. So in this case have a [2][3] array, and then put it back in the ArrayList after removing the whitespace. But that seems like a funny way to do it, and not scaleable if my list changed, like having an email on the end. Any thoughts? Thanks.

Edit: Dumber question, so I'm still not sure how I can process the data, because I can't do this right:

for (String s : myList) {
    String st[] = s.split(",\\s*");
}

since st[] will lose scope after the foreach loop. And if I declare String st[] beforehand, I wouldn't know how big to create my array right? Thanks.

A: 

you can use Sting.split() method in java or u can use split() method from google guava library's Splitter class as shown below

static final Splitter MY_SPLITTER = Splitter.on(',') .trimResults() .omitEmptyStrings();

Pangea
I suggest using StackOverflow with a browser or editor that provides spell checking services.
sarnold
May i know what your problem is. The post, I guess was helpful.
Pangea
The problem is that your post included a link to an interface the original poster was already using, an URL (not hyperlinked) for add-on code that isn't strictly necessary, and haven't yet fixed the spelling errors. (I'll happily remove my -1 if you or someone else fixes the spelling errors and corrects the guava link. And if you can show how the guava library can solve this problem, I'll even add in an +1.) In short: answers aren't static things, fix problems and votes can change. :)
sarnold
The original post did not include the code snippet. The author might have edited the post later. And now I've updated the sample code for guava library
Pangea
+2  A: 

If you use a regex for you split, you can specify, a comma followed by optional whitespace (which includes spaces and tabs just in case).

String[] fields = mystring.split(",\\s*");

Depending on whether you want to parse each line separately or not you may first want to create an array split on a line return

String[] lines = mystring.split("\\n");

Dunderklumpen
+1  A: 

Just split() on each line with the delimiter set as ',' to get an array of Strings with the extra whitespace, and then use the trim() method on the elements of the String array, perhaps as they are being used or in advance. Remember that the trim() method gives you back a new string object (a String object is immutable).

Chris Dennett
+3  A: 

You could just scan through the entire string and build a new string, skipping any whitespace that occurs after a comma. This would be more efficient than splitting and rejoining. Something like this should work:

String str = /* your original string from the array */;
StringBuilder sb = new StringBuilder();
boolean skip = true;

for (int i = 0; i < str.length(); i++) {
  char ch = str.charAt(i);

  if (skip && Character.isWhitespace(ch))
    continue;

  sb.append(ch);

  if (ch == ',')
    skip = true;
  else
    skip = false;
}

String result = sb.toString();
casablanca
I would appreciate a comment from whoever downvoted this.
casablanca
@casablanca, agreed, your example introduces a useful tool and very useful parsing idiom.
sarnold
+1  A: 

If I understood your problem, here is a solution:

    ArrayList<String> tmp = new ArrayList<String>();
    tmp.add("bob,      jones,    123-333-1111");
    tmp.add("    james, lee,  234-333-2222");

    ArrayList<String> fixedStrings = new ArrayList<String>();

    for (String i : tmp)    {
        System.out.println(i);
        String[] data = i.split(",");

        String result = "";
        for (int j = 0; j < data.length - 1; ++j)   {
            result += data[j].trim() + ", ";
        }

        result += data[data.length - 1].trim();

        fixedStrings.add(result);
    }

    System.out.println(fixedStrings.get(0));
    System.out.println(fixedStrings.get(1));

I guess it could be fixed not to create a second ArrayLis. But it's scalable, so if you get lines in the future like: "bob, jones , [email protected] , 123-333-1111 " it will still work.

A: 

Could be a bit more elegant, but it works...

ArrayList<String> strings = new ArrayList<String>();
strings.add("bob,      jones,    123-333-1111");
strings.add("james, lee,  234-333-2222");

for(int i = 0; i < strings.size(); i++) {
  StringBuilder builder = new StringBuilder();
  for(String str: strings.get(i).split(",\\s*")) {
    builder.append(str).append(" ");
  }
  strings.set(i, builder.toString().trim());
}

System.out.println("strings = " + strings);
S73417H
+1  A: 

I've had a lot of success using this library.

Robert Watkins