簡體   English   中英

如何大寫句子中字符串的首字母?

[英]How to capitalize the first letter of a string in a sentence?

我似乎僅在Java中使用String方法就找不到任何解決方案。 嘗試將字符串取出時遇到問題...

這是我的代碼:

import java.util.Scanner;
public class lab5_4
{
    public static void main(String[]args)
    {
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter a sentence");
        String s= scan.nextLine();
        String s2 = s.toLowerCase();

        for( int count = 0; count<= s2.length()-1; count++)
        {
            if( s2.charAt(count)==' ')
            {
                String s3 = s2.substring(count,count+1);
                String s4= s3.toUpperCase();
                System.out.print(s4);
            }
        }
    }
}

下列方法將輸入字符串中的所有字符都強制轉換為小寫字母(如默認Locale的規則所述),除非它前面緊跟一個“可操作的分隔符”,在這種情況下,該字符被強制轉換為大寫字母。

public static String toDisplayCase(String s) {

    final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
                                                 // to be capitalized

    StringBuilder sb = new StringBuilder();
    boolean capNext = true;

    for (char c : s.toCharArray()) {
        c = (capNext)
                ? Character.toUpperCase(c)
                : Character.toLowerCase(c);
        sb.append(c);
        capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
    }
    return sb.toString();
}

測試值

一個字符串

馬林·奧馬利

約翰·威爾克斯·布斯

還有另一個STRING

產出

弦樂

馬丁·奧馬利

約翰·威爾克斯·布斯

另一個弦

您似乎正在檢查空白,然后在其上調用toUpperCase() 您希望s3是下一個字符,因此它應該是String s3 = s2.substring(count+1, count+2);

您還將僅打印if評估為true的字符,而不是所有字符。 您需要將print語句置於if之外。 這不僅需要進行基本更改,而且還可以幫助您入門。

您可以使用模式從每個句子中選擇第一個字母,例如

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter a sentence");
        String s= scan.nextLine();
        String toCappital = capitalTheFirstLetter(s);
        System.out.println(toCappital);

    }

    public static String capitalTheFirstLetter(String sentence){
        StringBuilder stringBuilder = new StringBuilder(sentence.toLowerCase());
        Pattern pattern = Pattern.compile("\\s?([a-z])[a-z]*"); // ([a-z]) to group the first letter
        Matcher matcher = pattern.matcher(sentence.toLowerCase()); 
        while (matcher.find()) {
            String fistLetterToCapital = matcher.group(1).toUpperCase();
            stringBuilder.replace(matcher.start(1), matcher.end(1), fistLetterToCapital); // replace the letter with it capital
        }
        return stringBuilder.toString();
    }

}

輸出

Enter a sentence
how to capitalize the first letter of a string in a sentence ?
How To Capitalize The First Letter Of A String In A Sentence ?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM