-2

I want to convert every other letter in a string to capital. Say I have a string: "h3e5l!@lo461!28", I need to see if the character is a letter and then convert every other letter to capital. Here is my code right now but it doesn't work and I don't understand what to do to fix it.

public static void main(String[]args){
    String a = "h3e5l!@lo461!28" ;
    System.out.println(cap(a));
}

public static String cap(String a){
    for(int i = 0; i< a.length(); i++){
        if(Character.isLetter(a.charAt(i)) && i % 2 == 0){
            a.charAt(i) = a.toUpperCase();
        }
    }
    return a;
}
takendarkk
  • 2,949
  • 7
  • 22
  • 35
Dave
  • 49
  • 5

2 Answers2

1

You can use a StringBuilder object to collect all the processed characters and return the StringBuilder object in the end.

public class Main {
    public static void main(String[] args) {
        String a = "h3e5l!@lo461!28";

        System.out.println(cap(a));
    }

    public static String cap(String a) {
        int count = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < a.length(); i++) {
            char ch = a.charAt(i);
            // Capitalise every other letter
            if (Character.isLetter(ch) && (++count) % 2 == 0) {
                sb.append(Character.toUpperCase(ch));
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}

Output:

h3E5l!@Lo461!28
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
1

You're on the right track, but you can't replace individual characters in a String, you should instead use a char[] retrieved from String#toCharArray, like the following:

public static void main(String[]args){
   String a = "h3e5l!@lo461!28" ;
  
   System.out.println(cap(a));
}

public static String cap(String a){
    // count letters
    int letterCount = 0;
    char[] chars = a.toCharArray();

    for(int i = 0; i < chars.length; i++){   
        if(Character.isLetter(chars[i])) {
            letterCount += 1;
            if(letterCount % 2 == 0) { // every other letter
                chars[i] = Character.toUpperCase(chars[i]);
            }
        }
    }

    return new String(chars);
}
Jonny Henly
  • 3,725
  • 4
  • 23
  • 41