1

Im reading in a file and each line is as follows

Derek Simons, Jason baker
Jack Smith, Rob Thomson

The problem is with my tokenizer

StringTokenizer st = new StringTokenizer(line, ",");
    while(st.hasMoreTokens()){ 
       System.out.println(st.nextToken());
    }

the output is

Derek Simons
 Jason baker
Jack Smith
 Rob Thomson

how can I get rid of that extra blank space? so that the output would be

Derek Simons
Jason baker
Jack Smith
Rob Thomson

Any help is appreciated thanks!

xiao
  • 1,718
  • 4
  • 23
  • 31

4 Answers4

1

I don't know which programming language you are using, but in many languages there is something called Trim(). so you do s.Trim();, where s is the string. That will remove all blanks

Christian
  • 4,345
  • 5
  • 42
  • 71
1

You can avoid having to trim each string manually if the input is always in the form you describe:

String[] tokens = line.split(",\\s*")

Now tokens will contain each name without leading spaces in the second token.

sjr
  • 9,769
  • 1
  • 25
  • 36
0

Did you consider using the .trim method?

Returns a copy of the string, with leading and trailing whitespace omitted.

npinti
  • 51,780
  • 5
  • 72
  • 96
0

You could use trim() or even just specify you StringTokenizer's delimiter as ", " (a comma followed by a space) instead of just ",".

brent777
  • 3,369
  • 1
  • 26
  • 35