1

Hi guys I want to split this string "Ronald Andrade" in 2 var with StringTokenizer.

I have this code:

package domApli;
import java.util.StringTokenizer;

public class string {

public static void main(String[] args) {



    String paciente = "Ronald Andrade";
    String linea = paciente;
    StringTokenizer tokens = new StringTokenizer(linea);
    String a= "";
    while(tokens.hasMoreTokens()){
        a+=tokens.nextToken();
    }

    System.out.print(a);

}

}

I want to have something like this:

String x = "Ronald";
String y = "Andrade";
pb2q
  • 58,613
  • 19
  • 146
  • 147
falconR
  • 159
  • 11
  • Please don't forget to accept the answer that was most helpful for you, by clicking on the check mark to its left. I mention this because I've noticed that you haven't accepted a single answer in all your questions in stack exchange, and that's bad for your accept ratio. – Óscar López Jun 11 '12 at 22:05
  • Oh man, I'm sorry. I'll check my Q's – falconR Jun 11 '12 at 23:52

2 Answers2

3

Better use the split() method found in the String class, like this:

String[] data = paciente.split("\\s+");
String x = data[0];  // x = "Ronald"
String y = data[1];  // y = "Andrade"

For all practical purposes, StringTokenizer is deprecated and you should stop using it:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

The code you have posted will result the same as input. For the required result, try this code,

public static void main(String[] args) {

String paciente = "Ronald Andrade";
String linea = paciente;
StringTokenizer tokens = new StringTokenizer(linea);
String x= "";
String y= "";
int i = 0;
while(tokens.hasMoreTokens()){
 if ( i = 0) {
         x = tokens.nextToken();
  }
  i = i+1;
 else
  {
      y = tokens.nextToken();
   }

}

System.out.print(x);
 System.out.print(y);

}

This is a very crude and inefficient way though. It would be better if you prefer a split function. You could also use substring function. Both of them are quick enough.

Krishna
  • 169
  • 1
  • 8
  • I didn't have any idea how to use this method. I was thinking to use for instead an if. And yes, I'll use split, thanks ! – falconR Jun 12 '12 at 00:01