How do I capitalise the first letter of every sentence in a string? Should I use .capitalisedString
?
Asked
Active
Viewed 430 times
3

Tom Coomer
- 6,227
- 12
- 45
- 82
-
1See my answer here: https://stackoverflow.com/questions/2432452/how-to-capitalize-the-first-word-of-the-sentence-in-objective-c/24712107#24712107 – Ken Thomases Nov 27 '14 at 11:31
-
2@MaxMacLeod: Not a 100% duplicate. The referenced thread shows how to capitalize the first character of a string, not of each *sentence* in the string. – Martin R Nov 27 '14 at 12:14
-
1@MaxMacLeod No. Pay attention that this is about string with multiple sentences. Not just one string. – Kirsteins Nov 27 '14 at 12:18
-
ok I see it now point taken – Max MacLeod Nov 27 '14 at 12:22
2 Answers
4
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."

rintaro
- 51,423
- 14
- 131
- 139
-
It capitalises the first letter in the string, but the others at the beginning of the sentence are still lowercase. – Tom Coomer Nov 27 '14 at 13:06
-
(+1), but: Why `var _`? – The last two lines can be simplified slightly to `result += String(first).uppercaseString + substring` . – Martin R Nov 27 '14 at 13:42
-
There is actually a subtle problem here. Your method applied to `"toefl. abc."` yields `"Toefl. aBc."`. The reason is that the *ligature* "fl", when converted to upper case, becomes two characters: "FL" :) – Martin R Mar 26 '15 at 16:20
-1
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);
}

veera
- 1
-
Did you see that the question is about the Swift programming language? – Martin R Nov 27 '14 at 11:45