当对字符串进行修改的时候,需要使用StringBuffer和StringBuilder类。和String类不同的是,StringBuffer和StringBuilder类的对象能够被多次修改,并且不产生新的未使用对象。StringBuilder不是线程安全的,不能同步访问,这是它和StringBuffer之间最大的不同。
StringBuffer方法:
- public StringBuffer append(String s) 将指定的字符串追加到此字符序列
- public StringBuffer reverse() 将此序列用其反转形式取代
- public delete(int start, int end) 移除序列的子字符串中的字符
- public insert(int offset, int i) 将int参数的字符串表示形式插入此序列中
- replace(int start, int end, String str) 使用给定String中的字符替换此序列中的子字符串中的字符
示例代码:
public class Test{
public static void main(String args[]{
StringBuffer sb = new StringBuffer();
sb.append("java");
sb.append("StringBuffer");
sb.append("StringBuilder");
System.out.println(sb);
}
}
整数转罗马数字问题:
class Solution{
public String intToRoman(int num){
int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuilder sb = new StringBuilder();
for(int i=0;i<values.length&&num>0;i++){
while(values[i]<=num){
num -= values[i];
sb.append(symbols[i]);
}
}
return sb.toString();
}
}