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);
    }
}
            Asked
            
        
        
            Active
            
        
            Viewed 1,031 times
        
    -1
            
            
         
    
    
        Yassin Hajaj
        
- 21,337
- 9
- 51
- 89
 
    
    
        Shubham
        
- 25
- 9
- 
                    "not working"? May I ask you what makes you think that? – Yassin Hajaj Mar 15 '16 at 19:31
- 
                    2Java `String` is *immutable* (`s = s.setCharAt(i, ch);`), and you should prefer (the newer) `StringBuilder` to `StringBuffer`. Like `Vector` and `ArrayList`, some classes are only kept for compatibility. – Elliott Frisch Mar 15 '16 at 19:38
- 
                    still its not working when i use (s = s.setCharAt(i, ch);) and i am using net beans ide. – Shubham Mar 16 '16 at 17:56
2 Answers
0
            
            
        The setCharAt(...) function doesn't alter the string you are dealing with, it returns a new String with the requested changed character.
 
    
    
        Edwin Buck
        
- 69,361
- 7
- 100
- 138
0
            
            
        setCharAt not working with string but working with stringbuffer in JAVA why?
It is because setCharAt is a method from the StringBuilder class.
The String class does not have setCharAt method.
If you want to "set" a String, you have to reassign a new String value (new Sting object) back into the String variable.
 
    
    
        user3437460
        
- 17,253
- 15
- 58
- 106