Search code examples
javacharstringbuilderuppercase

I can't figure out a way to find a specific char in a stringbuilder and replace it with uppercase


For Example: Enter a String: aAaAaAaAaAaAbBbBbBbBbBbBbcCccccCCccCCCC

What character should be converted to uppercase? b

What the output should be: aAaAaAaAaAaABBBBBBBBBBBBBcCccccCCccCCCC

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter a String");
    StringBuilder sb = new StringBuilder(keyboard.nextLine());
    System.out.println("Which character should be converted to uppercase?");
    char c = keyboard.nextLine().charAt(0);

    ParsingUtils.changeLetter(sb, c);

    System.out.println(sb);
}

public static void changeLetter(StringBuilder sb, char letter)
{
    String change = Character.toString(letter); //changes the char in the parameter to string
    String change2 = change.toUpperCase(); //make an uppercase copy of the string
    char upper = change2.charAt(0); //change the upper case copy to a char

    for (int counter = 0; counter < sb.length(); counter++) //Is supposed to replace every instance of the given character with uppercase
    {
        if (sb.toString().contains(change))
        {
            sb.setCharAt(counter, upper);
        }
    }
}

What my code outputs: BBBBBBBBBBBBBBBBBBBBBBBBBcCccccCCccCCCC

Is there a better, less convoluted way to do this that I'm too frustrated to see?

I'm still a novice in Java so there is probably a simple answer that is going completely over my head.


Solution

    • The first three lines can be simplified to just:

      char upper = Character.toUpperCase(letter);
      
    • Use charAt(counter), rather than checking if the whole string builder contains the letter.

      if (sb.charAt(counter) == letter)
      

    Full code:

    public static void changeLetter(StringBuilder sb, char letter)
    {
        char upper = Character.toUpperCase(letter);
    
        for (int counter = 0; counter < sb.length(); counter++)
        {
            if (sb.charAt(counter) == letter)
            {
                sb.setCharAt(counter, upper);
            }
        }
    }