问题
How do I capitalise the first letter of every sentence in a string? Should I use .capitalisedString
?
回答1:
You can enumerate String
per sentences by using NSStringEnumerationOptions.BySentences
. But it detect a "sentence" only if the first character is upper-cased.
So, This may not be perfect, but you can try this:
import Foundation
let text:String = "lorem ipsum dolor elit, sed aliqfuas. imfs enim ad veniam, quis nostrud consequat? duis aute irure dolor in pariatur."
var result = ""
text.uppercaseString.enumerateSubstringsInRange(text.startIndex..<text.endIndex, options: .BySentences) { (_, range, _, _) in
// ^^^^^^^^^^^^^^^^ enumerate all upper cased string
var substring = text[range] // retrieve substring from original string
let first = substring.removeAtIndex(substring.startIndex)
result += String(first).uppercaseString + substring
}
// result -> "Lorem ipsum dolor elit, sed aliqfuas. Imfs enim ad veniam, quis nostrud consequat? Duis aute irure dolor in pariatur."
回答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);
}
来源:https://stackoverflow.com/questions/27169581/capitalise-first-letter-of-every-sentence