字符串示例

one thousand only
two hundred
twenty
seven

我如何改变一个大写字母的字符串的第一个字符,而不改变任何其他字母的情况?

更改之后应该是:

One thousand only
Two hundred
Twenty
Seven

注意:我不想使用apache.commons.lang.WordUtils来做这件事。


当前回答

我的函数方法。它在整个段落的白转义后将句子中的第一个字符颠倒。

如果只启用单词的第一个字符,只需删除.split(" ")

           b.name.split(" ")
                 .filter { !it.isEmpty() }
                 .map { it.substring(0, 1).toUpperCase() 
                 +it.substring(1).toLowerCase() }
                  .joinToString(" ")

其他回答

如果你只想大写一个名为input的字符串的第一个字母,其余的保持不变:

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

现在输出将有您想要的内容。在使用此方法之前,请检查您的输入至少是一个字符,否则将会出现异常。

把所有的东西加在一起,在字符串的开头修剪出额外的空白是一个好主意。否则,.substring(0, 1)。toUpperCase将尝试大写一个空白。

    public String capitalizeFirstLetter(String original) {
        if (original == null || original.length() == 0) {
            return original;
        }
        return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
    }
public static String capitalize(String str){
        String[] inputWords = str.split(" ");
        String outputWords = "";
        for (String word : inputWords){
            if (!word.isEmpty()){
                outputWords = outputWords + " "+StringUtils.capitalize(word);
            }
        }
        return outputWords;
    }

即使是“简单”的代码,我也会使用库。问题不是代码本身,而是已经存在的覆盖例外情况的测试用例。这可以是null,空字符串,其他语言中的字符串。

文字操作部分已经从Apache Commons Lang中移除。它现在被放置在Apache Commons Text中。通过https://search.maven.org/artifact/org.apache.commons/commons-text获取。

你可以使用WordUtils。大写(字符串str)从Apache公共文本。它比你想要的更强大。它也可以大写full(例如,固定“oNe thousand only”)。

由于它适用于完整的文本,所以必须告诉它只大写第一个单词。

WordUtils.capitalize("one thousand only", new char[0]);

完整的JUnit类,使发挥功能:

package io.github.koppor;

import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class AppTest {

  @Test
  void test() {
    assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
  }

}

使用StringTokenizer类的示例:

String st = "  hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){   
        st1=a.nextToken();
        f=Character.toUpperCase(st1.charAt(0));
        fs+=f+ st1.substring(1);
        System.out.println(fs);
}