setCharAt不使用字符串,但在JAVA中使用stringbuffer为什么?

时间:2016-03-15 19:30:19

标签: java

public class String2 {
    public static String alterstring(String s) {
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) != 'a' && s.charAt(i) != 'e' && s.charAt(i) != 'i' && s.charAt(i) != 'o' && s.charAt(i) != 'u') {
                int a = s.charAt(i);
                char ch = (char)(a + 1);
                s.setCharAt(i, ch);
            }
        }
        return s;
    }
    public static void main(String[] args) {
        String t;
        String s = new String();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a string:");
        String s = sc.nextLine();
        t = alterstring(s);
        System.out.println(t);
    }
}

2 个答案:

答案 0 :(得分:0)

setCharAt(...)函数不会改变您正在处理的字符串,它会返回一个带有请求更改字符的新String。

答案 1 :(得分:0)

  

setCharAt不使用字符串但在JAVA中使用stringbuffer为什么?

这是因为setCharAt是来自StringBuilder类的方法。

String班级 没有 setCharAt方法。

如果你想&#34;设置&#34;一个String,你必须将一个新的String值(新的Sting对象)重新分配给String变量。