例如:
String s =“这是a.line是.over”
应该出现
“这是a.Line is.Over”
我想过两次使用字符串标记符
-first split using"."
-second split using " " to get the first word
-then change charAt[0].toUpper
现在我不确定如何使用字符串标记符的输出作为另一个的输入?
我也可以使用split方法生成我试过的数组
String a="this is.a good boy";
String [] dot=a.split("\\.");
while(i<dot.length)
{
String [] sp=dot[i].split(" ");
sp[0].charAt(0).toUpperCase();// what to do with this part?
答案 0 :(得分:13)
使用StringBuilder,无需拆分和创建其他字符串,依此类推,请参阅代码
public static void main(String... args) {
String text = "this is a.line is. over";
int pos = 0;
boolean capitalize = true;
StringBuilder sb = new StringBuilder(text);
while (pos < sb.length()) {
if (sb.charAt(pos) == '.') {
capitalize = true;
} else if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
capitalize = false;
}
pos++;
}
System.out.println(sb.toString());
}
答案 1 :(得分:3)
无需捣乱分裂和拼接,您可以在字符数组上就地工作:
String s = "this is a.line is .over ";
char[] cs = s.toCharArray();
// make sure to capitalise the first letter in the string
capitaliseNextLetter(cs, 0);
for (int i = 0; i < cs.length; i++) {
// look for a period
if (cs[i] == '.') {
// capitalise the first letter after the period
i = capitaliseNextLetter(cs, i);
// we're assigning to i to skip the characters that
// `capitaliseNextLetter()` already looked at.
}
}
System.out.println(new String(cs));
// This will capitalise the first letter in the array `cs` found after
// the index `i`
private static int capitaliseNextLetter(char[] cs, int i) {
for (; i < cs.length; i++) {
// This will skip any non-letter after the space. Adjust the test
// as desired
if (Character.isAlphabetic(cs[i])) {
cs[i] = Character.toUpperCase(cs[i]);
return i;
}
}
return cs.length;
}
答案 2 :(得分:2)
尝试这样可以将句子的第一个字母大写。我刚刚对你的代码进行了一些修改。
public static void main(String[] args) {
String a = "this is.a good boy";
String[] dot = a.split("\\.");
int i = 0;
String output = "";
while (i < dot.length) {
dot[i] = String.valueOf(dot[i].charAt(0)).toUpperCase()
+ dot[i].substring(1);
output = output + dot[i] + ".";
i++;
}
System.out.println(output);
}
输出:
This is.A good boy.
答案 3 :(得分:1)
如果您可以使用WordUtils from Apache commons-lang3,请执行以下操作:
WordUtils.capitalizeFully(text, '.')
答案 4 :(得分:0)
请注意,Java字符串是不可变的(不可修改)。
另请注意,如果sp[0].charAt(0)
后面有空格,ArrayIndexOutOfBoundsException
会导致.
(从那时起第一个字符串将为空)。
我建议使用char[]
,例如:
String a = "this is.a good boy";
char arr[] = a.toCharArray();
boolean capitalize = true;
for (int i = 0; i < arr.length; i++)
if (arr[i] == '.')
capitalize = true;
else if (arr[i] != ' ' && capitalize)
{
arr[i] = Character.toUpperCase(arr[i]);
capitalize = false;
}
a = new String(arr);
Character.isWhitespace(arr[i])
可能优先于arr[i] != ' '
。
答案 5 :(得分:0)
char[] strArr = str.toCharArray();
for (int i = 0; i < strArr.length; i++) {
if (str.charAt(i) == " ".charAt(0) && i + 1 < strArr.length) {
strArr[i + 1] = String.valueOf(String.valueOf(strArr[i + 1])).toUpperCase().charAt(0);
}
}
System.out.println(String.valueOf(strArr));