问题描述:

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

相关阅读:
Top