我目前正在学习如何操作字符串,我认为我需要一段时间才能习惯。我想知道如何在每个句子的句点后将字母大写。
输出是这样的:
输入句子:我很高兴。这是天才。
大写:我很高兴。这是天才。
我已经尝试创建自己的代码但它不起作用,请随时更正和更改它。这是我的代码:
package Test;
import java.util.Scanner;
public class TestMain {
public static void main(String[]args) {
String sentence = getSentence();
int position = sentence.indexOf(".");
while (position != -1) {
position = sentence.indexOf(".", position + 1);
sentence = Character.toUpperCase(sentence.charAt(position)) + sentence.substring(position + 1);
System.out.println("Capitalized: " + sentence);
}
}
public static String getSentence() {
Scanner hold = new Scanner(System.in);
String sent;
System.out.print("Enter sentences:");
sent = hold.nextLine();
return sent;
}
}
棘手的部分是我如何将句点 (".") 后的字母大写?我没有很多字符串操作知识,所以我真的被困在这个领域。
最佳答案
试试这个:
package Test;
import java.util.Scanner;
public class TestMain {
public static void main(String[]args){
String sentence = getSentence();
StringBuilder result = new StringBuilder(sentence.length());
//First one is capital!
boolean capitalize = true;
//Go through all the characters in the sentence.
for(int i = 0; i < sentence.length(); i++) {
//Get current char
char c = sentence.charAt(i);
//If it's period then set next one to capital
if(c == '.') {
capitalize = true;
}
//If it's alphabetic character...
else if(capitalize && Character.isAlphabetic(c)) {
//...we turn it to uppercase
c = Character.toUpperCase(c);
//Don't capitalize next characters
capitalize = false;
}
//Accumulate in result
result.append(c);
}
System.out.println(result);
}
public static String getSentence(){
Scanner hold = new Scanner(System.in);
String sent;
System.out.print("Enter sentences:");
sent = hold.nextLine();
return sent;
}
}
这是做什么的,它按顺序推进字符串中的所有字符,并保持下一个字符需要大写的状态。
按照评论进行更深入的解释。
关于java - 如何使用java将每个句子中句号后的首字母大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32249723/