Capitalise first letter of every sentence

夙愿已清 提交于 2019-12-10 21:39:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!