我使用Java从用户获得一个字符串输入。我试着让输入的第一个字母大写。

我试了一下:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

这导致了以下编译错误:

类型不匹配:不能从InputStreamReader转换为BufferedReader 不能在基本类型char上调用toUppercase()


当前回答

给出的答案是只大写一个单词的第一个字母。使用以下代码将整个字符串大写。

public static void main(String[] args) {
    String str = "this is a random string";
    StringBuilder capitalizedString = new StringBuilder();
    String[] splited = str.trim().split("\\s+");

    for (String string : splited) {         
        String s1 = string.substring(0, 1).toUpperCase();
        String nameCapitalized = s1 + string.substring(1);

        capitalizedString.append(nameCapitalized);
        capitalizedString.append(" ");
    }
    System.out.println(capitalizedString.toString().trim());
}

输出: 这是一个随机字符串

其他回答

我发布的代码将从字符串中删除下划线(_)符号和额外的空格,而且它将大写字符串中每个新词的第一个字母

private String capitalize(String txt){ 
  List<String> finalTxt=new ArrayList<>();

  if(txt.contains("_")){
       txt=txt.replace("_"," ");
  }

  if(txt.contains(" ") && txt.length()>1){
       String[] tSS=txt.split(" ");
       for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }  
  }

  if(finalTxt.size()>0){
       txt="";
       for(String s:finalTxt){ txt+=s+" "; }
  }

  if(txt.endsWith(" ") && txt.length()>1){
       txt=txt.substring(0, (txt.length()-1));
       return txt;
  }

  txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
  return txt;
}

你可以试试这个

/**
 * capitilizeFirst(null)  -> ""
 * capitilizeFirst("")    -> ""
 * capitilizeFirst("   ") -> ""
 * capitilizeFirst(" df") -> "Df"
 * capitilizeFirst("AS")  -> "As"
 *
 * @param str input string
 * @return String with the first letter capitalized
 */
public String capitilizeFirst(String str)
{
    // assumptions that input parameter is not null is legal, as we use this function in map chain
    Function<String, String> capFirst = (String s) -> {
        String result = ""; // <-- accumulator

        try { result += s.substring(0, 1).toUpperCase(); }
        catch (Throwable e) {}
        try { result += s.substring(1).toLowerCase(); }
        catch (Throwable e) {}

        return result;
    };

    return Optional.ofNullable(str)
            .map(String::trim)
            .map(capFirst)
            .orElse("");
}

再举一个例子,如何让用户输入的第一个字母大写:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = br.readLine();
// handle supplementary characters
IntStream.concat(
        IntStream.of(string.codePointAt(0))
                .map(Character::toUpperCase), string.codePoints().skip(1)
)
.forEach(cp -> System.out.print(Character.toChars(cp)));
System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));

P.S = a是一个字符串。

StringUtils.capitalize(..) from commons-lang