Java – 使空格后的字符大写?

huangapple go评论80阅读模式
英文:

Java - Make character after space uppercase?

问题

public String toTitleCase(String phrase) {
    for (int i = 0; i < phrase.length(); i++) {
        if (phrase.substring(i, i + 1).equals(" ")) {
            phrase = phrase.replace(phrase.substring(i + 1, i + 2), phrase.substring(i + 1, i + 2).toUpperCase());
        }
    }
    return phrase;
}
英文:

I'm trying to have the letter after every space turn uppercase. Can someone tell me what's wrong with the following method? Given phrase "this is a test" it returns "ThIs Is A TesT" instead of "this Is A Test"

public String toTitleCase(String phrase) {
    for (int i=0; i&lt;phrase.length(); i++) {
	    if(phrase.substring(i,i+1).equals(&quot; &quot;)) {
		    phrase = phrase.replace(phrase.substring(i+1,i+2),phrase.substring(i+1,i+2).toUpperCase());
	    }
	}
	return phrase;
}

</details>


# 答案1
**得分**: 2

问题出在你的代码中[`String.replace`][1] 会替换在 `String` 中出现的每个目标字符而不仅仅是你想要替换的那个字符

你可以直接在字符数组上操作而不是在 `String` 上操作

```java
public static String toTitleCase(String phrase) {

    // 将字符串转换为字符数组
    char[] phraseChars = phrase.toCharArray();

    for (int i = 0; i < phraseChars.length - 1; i++) {
        if(phraseChars[i] == ' ') {
            phraseChars[i+1] = Character.toUpperCase(phraseChars[i+1]);
        }
    }

    // 将字符数组转换为字符串
    return String.valueOf(phraseChars);
}

  [1]: https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/String.html#replace(java.lang.CharSequence,java.lang.CharSequence)
英文:

The problem in your code is that String.replace replaces each target character present in the String, and not only the one you want.

You could work directly on an array of chars instead of on the String:

public static String toTitleCase(String phrase) {

    // convert the string to an array 
    char[] phraseChars = phrase.toCharArray();

    for (int i = 0; i &lt; phraseChars.length - 1; i++) {
        if(phraseChars[i] == &#39; &#39;) {
            phraseChars[i+1] = Character.toUpperCase(phraseChars[i+1]);
        }
    }

    // convert the array to string
    return String.valueOf(phraseChars);
}

答案2

得分: 1

以下是翻译好的部分:

它正在替换所有的`t`,请尝试下面的代码。

它会帮助你。

String phrase = "this is a test";
for (int i = 0; i < phrase.length(); i++) {
    if (phrase.substring(i, i + 1).equals(" ")) {
        System.out.println(phrase.substring(i + 1, i + 2));
        phrase = phrase.replace(phrase.substring(i, i + 2), phrase.substring(i, i + 2).toUpperCase());
    }
}
System.out.println(phrase);
英文:

It's replacing all t, try below code.

It will help you.

 String phrase=&quot;this is a test&quot;;
            for (int i=0; i&lt;phrase.length(); i++) {
                if(phrase.substring(i,i+1).equals(&quot; &quot;)) {
                    System.out.println(phrase.substring(i+1,i+2));
                    phrase = phrase.replace(phrase.substring(i,i+2),phrase.substring(i,i+2).toUpperCase());
                }
            }
System.out.println(phrase);

答案3

得分: 1

使用流(或分割函数)将你的字符串分割成部分,不要手动使用子字符串进行分割。

尝试以下代码:

        String test = "this is a test";

        UnaryOperator<String> capitalize = str ->
                str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase();

        String result =
                Stream.of(
                        test.split(" ")
                ).map(capitalize)
                .collect(
                        Collectors.joining(" ")
                );

        System.out.println(result);

输出结果:This Is A Test

英文:

Use streams (or split) to split your string into parts, don't do it manually using substring.

Try below code

        String test = &quot;this is a test&quot;;

        UnaryOperator&lt;String&gt; capitalize = str -&gt;
                str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase();

        String result =
                Stream.of(
                        test.split(&quot; &quot;)
                ).map(capitalize)
                .collect(
                        Collectors.joining(&quot; &quot;)
                );

        System.out.println(result);

Output: This Is A Test

答案4

得分: 1

当您替换子字符串时,它会替换该子字符串的每个出现次数,而不一定是您要替换的目标。这就是为什么它会在单词内部替换字母。

在这里切换到使用 StringBuilder 来逐个处理字符。请注意,我们不会遍历整个字符串,因为在最后一个字符处没有下一个字符可大写。

public String toTitleCase(String phrase) {
  StringBuilder sb = new StringBuilder(phrase);
  for (int index = 0; index < phrase.length() - 1; ++index) {
    if (sb.charAt(index) == ' ') {
      sb.setCharAt(index + 1, Character.toUpperCase(sb.charAt(index + 1)));
    }
  }
  return sb.toString();
}
英文:

When you replace a substring it will replace the each occurrence of that substring - which is not necessarily the one you are trying to replace. This is why it is replacing letters inside words.

Switching to a StringBuilder here to poke individual characters. Note that we don't traverse the entire String because there is no next-character to capitalize at the last character.

public String toTitleCase(String phrase) {
  StringBuilder sb = new StringBuilder(phrase);
  for (int index = 0 ; index &lt; phrase.length - 1 ; ++index) {
    if (sb.charAt(index) == &#39; &#39;) {
      sb.setCharAt(index + 1, Character.toUppercase(sb.charAt(index + 1)));
    }
  }
  return sb.toString();
}

答案5

得分: 1

如果一个字母在任何单词中首次出现,它将在所有地方被替换。在您的情况下,所有的 t,i 和 a 将会变成大写字母。
is 为例。它会找到前面的空格。然后在条件体中,实际发生的情况是:

phrase = phrase.replace("i", "I");

并且所有的 i 都会被替换为 I。
String 类无法在特定位置进行替换。

你有两个选择:

  • 使用可以在特定位置进行替换的 StringBuilder。
String toTitleCase(String phrase) {
    StringBuilder sb = new StringBuilder(phrase);
    for (int i = 0; i < phrase.length(); i++) {
        if (i == 0 || phrase.charAt(i - 1) == ' ') {
            sb.replace(i, i + 1, phrase.substring(i, i + 1).toUpperCase());
        }
    }
    return sb.toString();
}
  • 或者使用流(stream)的方法,这是我推荐的方法,因为只有一行代码。这种方式不会保留空白(多个连续的空白会被替换为一个空格),但通常您会希望这样。
Arrays.asList(phrase.split("\\s+")).stream()
    .map(x -> x.substring(0, 1).toUpperCase() + x.substring(1))
    .collect(Collectors.joining(" "));
英文:

If a letter is first in any word, it will be replaced everywhere. In your case, all t,i and a will be uppercase.
Taking example for is. It is find a space before. Than in if body, what actually happen:

phrase = phrase.replace(&quot;i&quot;,&quot;I&quot;); 

And all i are replaced with I.
String class cannot replace at a specific position.

You have to options:

  • using StringBuilder which can replace at a specific position.
String toTitleCase(String phrase) {
        StringBuilder sb= new StringBuilder(phrase);
        for (int i=0; i&lt;phrase.length(); i++) {
            if(i==0 || phrase.charAt(i-1)==&#39; &#39;) {
                sb.replace(i,i+1,phrase.substring(i,i+1).toUpperCase());
            }
        }
        return sb.toString();
    }
  • or with stream, which is the method I prefer because is one-line. This way you don't preserve white-spaces( multiple consecutive white-spaces will be replaced with only one space), but usually you want this.
Arrays.asList(phrase.split(&quot;\\s+&quot;)).stream().map(x-&gt;x.substring(0,1).toUpperCase()+x.substring(1)).collect(Collectors.joining(&quot; &quot;));

huangapple
  • 本文由 发表于 2020年8月21日 19:26:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63522001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定