简体   繁体   English

如何将java中字符串中每个单词的第一个和最后一个字母大写

[英]How to capitalize the first and last letters of every word in a string in java

How to capitalize the first and last letters of every word in a string 如何大写字符串中每个单词的第一个和最后一个字母

i have done it this way - 我这样做了 -

    String cap = "";
    for (int i = 0; i < sent.length() - 1; i++)
    {
        if (sent.charAt(i + 1) == ' ')
        {
            cap += Character.toUpperCase(sent.charAt(i)) + " " + Character.toUpperCase(sent.charAt(i + 2));
            i += 2;
        }
        else
            cap += sent.charAt(i);
    }
    cap += Character.toUpperCase(sent.charAt(sent.length() - 1));
    System.out.print (cap);

It does not work when the first word is of more than single character 当第一个单词超过单个字符时,它不起作用

Please use simple functions as i am a beginner 请使用简单的功能,因为我是初学者

Using apache commons lang library it becomes very easy to do: 使用apache commons lang变得非常容易:

    String testString = "this string is needed to be 1st and 2nd letter-uppercased for each word";

    testString = WordUtils.capitalize(testString);
    testString = StringUtils.reverse(testString);
    testString = WordUtils.capitalize(testString);
    testString = StringUtils.reverse(testString);
    System.out.println(testString);

ThiS StrinG IS NeedeD TO BE 1sT AnD 2nD Letter-uppercaseD FoR EacH WorD ThiS StrinG需要1sT和2nD字母 - 大写字母EHH WorD

You should rather split your String with a whitespace as character separator, then for each token apply toUpperCase() on the first and the last character and create a new String as result. 您应该使用空格作为字符分隔符来拆分String,然后对于每个标记,在第一个和最后一个字符上应用toUpperCase()并创建一个新的String作为结果。

Very simple sample : 很简单的样品:

  String cap = "";
  String sent = "hello  world. again.";

  String[] token = sent.split("\\s+|\\.$");

  for (String currentToken : token){
      String firstChar = String.valueOf(Character.toUpperCase(currentToken.charAt(0)));
      String between = currentToken.substring(1, currentToken.length()-1);
      String LastChar = String.valueOf(Character.toUpperCase(currentToken.charAt(currentToken.length()-1)));
      if (!cap.equals("")){
        cap += " ";
      }
      cap += firstChar+between+LastChar; 
  }

Of course you should favor the use of StringBuilder over String as you perform many concatenations. 当然,在执行多个连接时,您应该支持在String上使用StringBuilder。

Output result : HellO World. AgaiN 输出结果: HellO World. AgaiN HellO World. AgaiN

Your code is missing out the first letter of the first word. 你的代码遗漏了第一个单词的第一个字母。 I would treat this as a special case, ie 我会把这视为特例,即

cap = ""+Character.toUpperCase(sent.charAt(0));
for (int i = 1; i < sent.length() - 1; i++)
{
.....

Of course, there are much easier ways to do what you are doing. 当然,有更简单的方法来做你正在做的事情。

Basically you just need to iterate over all characters and replace them if one of the following conditions is true: 基本上,如果满足下列条件之一,您只需迭代所有字符并替换它们:

  • it's the first character 这是第一个角色
  • it's the last character 这是最后一个角色
  • the previous character was a whitespace (or whatever you want, eg punctuation - see below) 前一个字符是一个空格(或任何你想要的,例如标点符号 - 见下文)
  • the next character is a whitespace (or whatever you want, eg punctuation - see below) 下一个字符是空格(或任何你想要的,例如标点符号 - 见下文)

If you use a StringBuilder for performance and memory reasons (don't create a String in every iteration which += would do) it could look like this: 如果你出于性能和内存的原因使用StringBuilder (不要在+=会做的每次迭代中创建一个String ),它可能如下所示:

StringBuilder sb = new StringBuilder( "some words    in a list   even with    longer    whitespace in between" );
for( int i = 0; i < sb.length(); i++ ) {
  if( i == 0 || //rule 1
      i == (sb.length() - 1 ) || //rule 2
      Character.isWhitespace( sb.charAt( i - 1 ) ) || //rule 3
      Character.isWhitespace( sb.charAt( i + 1 ) ) ) { //rule 4
    sb.setCharAt( i, Character.toUpperCase( sb.charAt( i ) ) );
  }
}

Result: SomE WordS IN A LisT EveN WitH LongeR WhitespacE IN BetweeN 结果: SomE WordS IN A LisT EveN WitH LongeR WhitespacE IN BetweeN

If you want to check for other rules as well (eg punctuation etc.) you could create a method that you call for the previous and next character and which checks for the required properties. 如果您还想检查其他规则(例如标点符号等),您可以创建一个方法,您可以调用上一个和下一个字符,并检查所需的属性。

String stringToSearch = "this string is needed to be first and last letter uppercased for each word";

    // First letter upper case using regex
Pattern firstLetterPtn = Pattern.compile("(\\b[a-z]{1})+");
Matcher m = firstLetterPtn.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()){
    m.appendReplacement(sb,m.group().toUpperCase()); 
}
m.appendTail(sb);
stringToSearch = sb.toString();
sb.setLength(0);

    // Last letter upper case using regex
Pattern LastLetterPtn = Pattern.compile("([a-z]{1}\\b)+");
m = LastLetterPtn.matcher(stringToSearch);
while(m.find()){
    m.appendReplacement(sb,m.group().toUpperCase()); 
}
m.appendTail(sb);
System.out.println(sb.toString());

output:

ThiS StrinG IS NeedeD TO BE FirsT AnD LasT LetteR UppercaseD FoR EacH WorD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM