java—我想不出在stringbuilder中找到特定字符并用大写字母替换它的方法

yx2lnoni  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(351)

例如:输入字符串:aaaaaaaaaa bbbbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
什么字符应该转换成大写?b
输出应该是什么:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

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);
        }
    }
}

我的代码输出什么:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
有没有一个更好的,不太复杂的方法来做这件事,我太沮丧看到?
我还是一个java新手,所以可能有一个简单的答案完全出乎我的意料。

jdzmm42g

jdzmm42g1#

前三行可以简化为:

char upper = Character.toUpperCase(letter);

使用 charAt(counter) ,而不是检查整个字符串生成器是否包含字母。

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

完整代码:

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);
        }
    }
}

相关问题