简体   繁体   中英

how can i split a string

Hi I want to split a string as only two parts. ie I want to split this string only once.

EX: String-----> hai,Bye,Go,Run 

I want to split the above string with comma(,) as two parts only

ie

String1 ---> hai 

String2 ---->Bye,Go,Run

Please help me how can I do it.

使用String.split(String regex,int limit)方法:

String[] result = string.split(",", 2);
String[] result = string.split("\\s*,\\s*" ,2);

This is a very basic Java knowledge... Have a look at String class definition before asking here: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

You should follow some Java tutorial before starting programming in Java.

if you check out the Java Doc of string

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

You'll find one of the methods is

split(String regex) 

then what you want is to use a regex like "," to get a table of strings

String str = "hai,Bye,Go,Run";
String str1 = str.substring(0, str.indexOf(','));
String str2 = str.substring(str.indexOf(',')+1);

You can use the String method:

public String[] split(String regex, int limit)

eg (not tested)

String str = "hai,Bye,Go,Run"
str.split(",", 2);
String str="hai,Bye,Go,Run";

//String 1

String str1=str.substring(0,str.indexOf(','));

//String 1

String str1=str.substring(str.indexOf(',')+1,str.length);

done :)

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