简体   繁体   中英

splitting the String using StringTokenizer in Java

I have recently started learning Java. I got stuck on Splitting the particular string. Here is the string:

String head = "(*, grandparent(X,Y))";

I want to split the string such that it will give two tokens. The two tokens should be * and grandparent(X,Y) . I have tried to split it by

StringTokenizer st=new StringTokenizer(head,",");
System.out.println("The tokens are: " + st.countTokens());

But I am getting three tokens if I split it by comma.

I don't want to split it by regex. Could you guys please help me?

If you always have 2 tokens you can specify the limit for number of tokens generated with String.split

For example: String[] tokens = head.split(",", 2)

Please don't use StringTokenizer in new code, its usage has been discouraged for a while in favor of newer better ways of doing similar work.

You could find the first comma using indexOf(',') .

Example:

String head="(*, grandparent(X,Y))";

int idx = head.indexOf(',');

String sub1 = head.substring(1, idx);
String sub2 = head.substring(idx + 1, head.length() - 1);

System.out.println("sub1 = " + sub1);
System.out.println("sub2 = " + sub2);

You can use the Splitter from guava as following:

String head="(*, grandparent(X,Y))";

Iterable<String> tokens = Splitter.on(",").limit(2).split(head);

for(String token : tokens){
    System.out.println(token);
}

Below the maven dependency to add to your pom.xml

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>

Hi I suggest to try this piece of code. It's a hack that works, depending on the content of the head string. For the shared value of head, it will work.

head=head.replace("*,","*;");
StringTokenizer st=new StringTokenizer(head,";");

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM