当前位置: 技术问答>java相关
String的问题(split)
来源: 互联网 发布时间:2015-05-22
本文导语: 把一个String分成一个String数组 比如 String a = "this is a string"; 我想得到的是 String[] b = {"this", "is", "a", "string"}; 就是需要一个类似perl中的split的函数 java中有这样的函数吗? 还是需要我自己写一个? ...
把一个String分成一个String数组
比如
String a = "this is a string";
我想得到的是
String[] b = {"this", "is", "a", "string"};
就是需要一个类似perl中的split的函数
java中有这样的函数吗?
还是需要我自己写一个?
比如
String a = "this is a string";
我想得到的是
String[] b = {"this", "is", "a", "string"};
就是需要一个类似perl中的split的函数
java中有这样的函数吗?
还是需要我自己写一个?
|
StringTokenizer......
|
String[] split(String regex)
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
|
import java.util.StringTokenizer;
.........
StringTokenizer stTemp = new StringTokenizer("this is a string"," ");//" "是空格
String[] b = new String[5];
int mIntCount = 0;
while(stTemp.hasMoreTokens())
{
try
{
b[mIntCount] = stTemp.nextToken();
System.out.println(b[mIntCount]);
mIntCount++;
}
catch(Exception e1)
{
}
}
.........
StringTokenizer stTemp = new StringTokenizer("this is a string"," ");//" "是空格
String[] b = new String[5];
int mIntCount = 0;
while(stTemp.hasMoreTokens())
{
try
{
b[mIntCount] = stTemp.nextToken();
System.out.println(b[mIntCount]);
mIntCount++;
}
catch(Exception e1)
{
}
}
|
可以用Vector
import java.util.StringTokenizer;
.........
StringTokenizer stTemp = new StringTokenizer("this is a string"," ");//" "是空格
Vector b = new Vector();
while(stTemp.hasMoreTokens())
{
try
{
String temp = stTemp.nextToken();
System.out.println(temp);
b.addElement(temp);
}
catch(Exception e1)
{
}
}
import java.util.StringTokenizer;
.........
StringTokenizer stTemp = new StringTokenizer("this is a string"," ");//" "是空格
Vector b = new Vector();
while(stTemp.hasMoreTokens())
{
try
{
String temp = stTemp.nextToken();
System.out.println(temp);
b.addElement(temp);
}
catch(Exception e1)
{
}
}
|
StringTokenizer类
|
还是StringTokenizer效率最高,不用寻求那么多答案,选最优的吧
|
public String[] stringSplit(String sourceString, String spliter)
{
String S1 = sourceString;
String S2 = spliter;
if(S1==null||S2==null||S1.equals("")||S2.equals(""))
{
return null;
}
else if(S1.length()
{
String S1 = sourceString;
String S2 = spliter;
if(S1==null||S2==null||S1.equals("")||S2.equals(""))
{
return null;
}
else if(S1.length()