Domanda

I have my code here that would like to change Stringtokenizer to String because the information I get is in sentence and I would like to cut it down to certain part.

StringTokenizer numberOfPost_string = new StringTokenizer( numberOfPost_text , delimiters );

System.out.println( numberOfPost_string.nextToken() );

int numberOfPost = Integer.parseInt(numberOfPost_string);

The problem I encounter is on the line int numberOfPost = Integer.parseInt(numberOfPost_string); where it gives me error.

Or is there other way for me to cut down sentence and convert it to integer?

È stato utile?

Soluzione

You probably want to use the return value of nextToken:

StringTokenizer numberOfPost_string = new StringTokenizer( numberOfPost_text , delimiters );
int numberOfPost = Integer.parseInt(numberOfPost_string.nextToken());

You can also do it with split: (although this is probably slightly less efficient)

int numberOfPost = Integer.parseInt(numberOfPost_text.split(delimiters)[0]);

Keep in mind that split takes a regular expression String, thus to specify multiple options for characters, you will need to surround them by []. To specify ;, , or ::

String delimiters = "[;,:]";

Altri suggerimenti

To convert the tokens to string

String x = "";
StringTokenizer in = new StringTokenizer(str, ",;");
while(in.hasMoreTokens()) {
    x = x + in.nextToken().toString();
}
System.out.print(x);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top