我似乎无法在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);
}
}
}
}
答案 0 :(得分:2)
以下方法将输入字符串中的所有字符强制为小写(如默认Locale
的规则所述),除非它后面紧跟一个&#34;可操作的分隔符&#34;在这种情况下,角色被强制成大写。
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();
}
测试值
一个字符串
maRTin o&#39; maLLEY
john wilkes-booth
另一个字符串
<强> OUTPUTS 强>
字符串
Martin O&#39; Malley
John Wilkes-Booth
又一个字符串
答案 1 :(得分:0)
您似乎正在检查空格,然后在其上调用toUpperCase()
。您希望s3成为下一个字符,因此它应该是String s3 = s2.substring(count+1, count+2);
。
您也只打印将if
评估为true而不是所有字符的字符。您需要print语句在if
之外。这将需要更多的基本更改,但这应该可以帮助您入门。
答案 2 :(得分:0)
您可以使用模式选择每个句子的第一个字母 这里有一个例子
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 ?