java中String常见问题

java中String常见问题

1.字符串比较==和equals

==:比较的是对象,判断两个引用的是否为同一内存地址(物理对象)

equals:比较的是值

2.通过空白字符拆封字符串

str.spilt("\s+")

以上支持:空白字符" "、换行" "、tab制表符" "、回车" "。

3.拼接重复的字符串

  3.1 common类的stringutils工具方法

String str = "abcd";  
String repeated = StringUtils.repeat(str,3);//abcdabcdabcd 

  3.2 StringBuilder方法人工构造

String src = "name";  
int len = src.length();  
int repeat = 5;  
StringBuilder builder = new StringBuilder(len * repeat);  
for(int i=0; i<repeat; i++){  
  builder.append(src);  
}  
String dst = builder.toString(); 

4.统计字符串中的某个字符的重复次数

  利用已有的工具类方法

int n = StringUtils.countMatches("11112222", "1"); 

另,可利用char[],循环计算。

原文地址:https://www.cnblogs.com/eric-fang/p/5157726.html