3

How do I capitalise the first letter of every sentence in a string? Should I use .capitalisedString?

Tom Coomer
  • 6,227
  • 12
  • 45
  • 82

2 Answers2

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