我已经使用 StringTokenizer 和 String 的方法 indexOf() 和 substring() 进行了拆分测试。结果我必须知道,第二个比 StringTokenizer 快。但我的问题是哪个最适合线程安全?
使用 StringTokenizer 进行字符串拆分:
String sample=null;
StringTokenizer tokens = new StringTokenizer("FF#Mukil","#");
if(tokens.hasMoreTokens())
{
sample= tokens.nextToken();
System.out.println(sample);
}
使用 String 的方法拆分字符串:
String sample= "FF#Mukil";
int pos=sample.indexOf('#');
System.out.println(sample.substring(0,pos));
在这些示例中,样本是全局变量提前致谢
编辑:在前面的第一个示例如下
StringTokenizer tokens = new StringTokenizer("FF#Mukil","#");
if(tokens.hasMoreTokens())
{
String sample= tokens.nextToken();
System.out.println(sample);
}
我已经改变了它,如下所示
String sample=null;
StringTokenizer tokens = new StringTokenizer("FF#Mukil","#");
if(tokens.hasMoreTokens())
{
sample= tokens.nextToken();
System.out.println(sample);
}
编辑:添加了 java 文件源。
//FileName=MySplitUtil.java
import javax.servlet.http.HttpServletRequest;
import java.util.StringTokenizer;
public class MySplitUtil
{
public static void setUsername_locale(HttpServletRequest request)
{
String value = (String) request.getAttribute("userLocale"); // userLocale's sample value looks like ffmukil$en_US
splite1(value,request);
splite2(value,request);
}
private static void splite1(String value,HttpServletRequest request)
{
StringTokenizer tokens = new StringTokenizer(value,"$");
String username=null;
String locale=null;
if(tokens.hasMoreTokens())
{
username = tokens.nextToken();
locale = tokens.nextToken();
}
request.setAttribute("usrName",username);
request.setAttribute("usr_Locale",locale);
}
private static void splite2(String value,HttpServletRequest request)
{
int pos = value.indexOf('$');
String username = value.substring(0,pos);
String locale = value.substring(pos+1,value.length());
request.setAttribute("usrName",username);
request.setAttribute("usr_Locale",locale);
}
}