字符传处理
StringTokenizer 属于 java.util 包,用于分隔字符串。
import java.util.*;
public class Test{
public static void main(String[] args) {
String str = "runoob,google,taobao,facebook,zhihu";
// 以 , 号为分隔符来分隔字符串
StringTokenizer tokenizer=new StringTokenizer(str,",");
while(tokenizer.hasMoreElements()) {
String repository = tokenizer.nextToken().trim();
System.out.println(repository);
}
}
}
字符串属性替换
public class Test{
public static void main(String[] args) {
String str = "${lang} a ${le}";
System.out.println(replace(str));
}
public static String replace(String str){
String result = str;
int pos_start = str.indexOf("${");
if (pos_start >= 0) {
StringBuilder builder = new StringBuilder();
int pos_end = -1;
while (pos_start >= 0) {
builder.append(str, pos_end + 1, pos_start);
pos_end = str.indexOf('}', pos_start + 2);
if (pos_end < 0) {
pos_end = pos_start - 1;
break;
}
String propName = str.substring(pos_start + 2, pos_end);
String replacement;
if (propName.length() == 0) {
replacement = null;
//TODO 可以根据不同的属性名称进行解析获取数据
}else{
replacement = propName;
}
if (replacement != null) {
builder.append(replacement);
} else {
builder.append(str, pos_start, pos_end + 1);
}
pos_start = str.indexOf("${", pos_end + 1);
}
builder.append(str, pos_end + 1, str.length());
result = builder.toString();
}
return result;
}
}