如何在android中将字符串转换为标题大小写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12387492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a string to title case in android?
提问by Russ
I searched high and low but could only find indirect references to this type of question. When developing an android application, if you have a string which has been entered by the user, how can you convert it to title case (ie. make the first letter of each word upper case)? I would rather not import a whole library (such as Apache's WordUtils).
我搜索了高低,但只能找到对此类问题的间接引用。在开发android应用程序时,如果您有一个用户输入的字符串,您如何将其转换为标题大小写(即,使每个单词的第一个字母大写)?我宁愿不导入整个库(例如 Apache 的 WordUtils)。
回答by Codeversed
Put this in your text utilities class:
把它放在你的文本实用程序类中:
public static String toTitleCase(String str) {
if (str == null) {
return null;
}
boolean space = true;
StringBuilder builder = new StringBuilder(str);
final int len = builder.length();
for (int i = 0; i < len; ++i) {
char c = builder.charAt(i);
if (space) {
if (!Character.isWhitespace(c)) {
// Convert to title case and switch out of whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
space = false;
}
} else if (Character.isWhitespace(c)) {
space = true;
} else {
builder.setCharAt(i, Character.toLowerCase(c));
}
}
return builder.toString();
}
回答by Russ
I got some pointers from here: Android,need to make in my ListView the first letter of each word uppercase, but in the end, rolled my own solution (note, this approach assumes that all words are separated by a single space character, which was fine for my needs):
我从这里得到了一些提示:Android,需要在我的 ListView 中使每个单词的第一个字母大写,但最后,推出了我自己的解决方案(注意,这种方法假设所有单词都由一个空格字符分隔,即很适合我的需要):
String[] words = input.getText().toString().split(" ");
StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
}
}
String titleCaseValue = sb.toString();
...where input is an EditText view. It is also helpful to set the input type on the view so that it defaults to title case anyway:
...其中输入是一个 EditText 视图。在视图上设置输入类型也很有帮助,以便它无论如何都默认为标题大小写:
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
回答by SLaks
You're looking for Apache's WordUtils.capitalize()
method.
您正在寻找 Apache 的WordUtils.capitalize()
方法。
回答by Ankitkumar Makwana
this helps you
这对你有帮助
EditText view = (EditText) find..
String txt = view.getText();
txt = String.valueOf(txt.charAt(0)).toUpperCase() + txt.substring(1, txt.length());
回答by zeeshan
In the XML, you can do it like this:
在 XML 中,您可以这样做:
android:inputType="textCapWords"
Check the reference for other options, like Sentence case, all upper letters, etc. here:
在此处检查其他选项的参考,例如句子大小写、所有大写字母等:
http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
回答by SafaOrhan
Here is the WordUtils.capitalize() method in case you don't want to import the whole class.
这是 WordUtils.capitalize() 方法,以防您不想导入整个类。
public static String capitalize(String str) {
return capitalize(str, null);
}
public static String capitalize(String str, char[] delimiters) {
int delimLen = (delimiters == null ? -1 : delimiters.length);
if (str == null || str.length() == 0 || delimLen == 0) {
return str;
}
int strLen = str.length();
StringBuffer buffer = new StringBuffer(strLen);
boolean capitalizeNext = true;
for (int i = 0; i < strLen; i++) {
char ch = str.charAt(i);
if (isDelimiter(ch, delimiters)) {
buffer.append(ch);
capitalizeNext = true;
} else if (capitalizeNext) {
buffer.append(Character.toTitleCase(ch));
capitalizeNext = false;
} else {
buffer.append(ch);
}
}
return buffer.toString();
}
private static boolean isDelimiter(char ch, char[] delimiters) {
if (delimiters == null) {
return Character.isWhitespace(ch);
}
for (int i = 0, isize = delimiters.length; i < isize; i++) {
if (ch == delimiters[i]) {
return true;
}
}
return false;
}
Hope it helps.
希望能帮助到你。
回答by gMale
I just had the same problem and solved it with this:
我刚刚遇到了同样的问题并用这个解决了它:
import android.text.TextUtils;
...
String[] words = input.split("[.\s]+");
for(int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0,1).toUpperCase()
+ words[i].substring(1).toLowerCase();
}
String titleCase = TextUtils.join(" ", words);
Note, in my case, I needed to remove periods, as well. Any characters that need to be replaced with spaces can be inserted between the square braces during the "split." For instance, the following would ultimately replace underscores, periods, commas or whitespace:
请注意,就我而言,我也需要删除句号。在“拆分”期间,可以在方括号之间插入任何需要用空格替换的字符。例如,以下内容最终将替换下划线、句点、逗号或空格:
String[] words = input.split("[_.,\s]+");
This, of course, can be accomplished much more simply with the "non-word character" symbol:
当然,这可以使用“非单词字符”符号更简单地完成:
String[] words = input.split("\W+");
It's worth mentioning that numbers and hyphens AREconsidered "word characters" so this last version met my needs perfectly and hopefully will help someone else out there.
值得一提的是,数字和连字符ARE所以这最后一个版本满足我的需求完美地认为是“单词字符”,希望能帮助别人那里。
回答by mossman252
Just do something like this:
只是做这样的事情:
public static String toCamelCase(String s){
if(s.length() == 0){
return s;
}
String[] parts = s.split(" ");
String camelCaseString = "";
for (String part : parts){
camelCaseString = camelCaseString + toProperCase(part) + " ";
}
return camelCaseString;
}
public static String toProperCase(String s) {
return s.substring(0, 1).toUpperCase() +
s.substring(1).toLowerCase();
}
回答by Angel Koh
I simplified the accepted answer from @Russ such that there is no need to differentiate the first word in the string array from the rest of the words. (I add the space after every word, then just trim the sentence before returning the sentence)
我简化了@Russ 接受的答案,这样就不需要将字符串数组中的第一个单词与其余单词区分开来。(我在每个单词后添加空格,然后在返回句子之前修剪句子)
public static String toCamelCaseSentence(String s) {
if (s != null) {
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
sb.append(toCamelCaseWord(words[i]));
}
return sb.toString().trim();
} else {
return "";
}
}
handles empty strings (multiple spaces in sentence) and single letter words in the String.
处理空字符串(句子中有多个空格)和字符串中的单字母单词。
public static String toCamelCaseWord(String word) {
if (word ==null){
return "";
}
switch (word.length()) {
case 0:
return "";
case 1:
return word.toUpperCase(Locale.getDefault()) + " ";
default:
char firstLetter = Character.toUpperCase(word.charAt(0));
return firstLetter + word.substring(1).toLowerCase(Locale.getDefault()) + " ";
}
}
回答by ErickBergmann
I wrote a code based on Apache's WordUtils.capitalize() method. You can set your Delimiters as a Regex String. If you want words like "of" to be skipped, just set them as a delimiter.
我写了一个基于 Apache 的 WordUtils.capitalize() 方法的代码。您可以将分隔符设置为正则表达式字符串。如果您希望跳过诸如“of”之类的单词,只需将它们设置为分隔符即可。
public static String capitalize(String str, final String delimitersRegex) {
if (str == null || str.length() == 0) {
return "";
}
final Pattern delimPattern;
if (delimitersRegex == null || delimitersRegex.length() == 0){
delimPattern = Pattern.compile("\W");
}else {
delimPattern = Pattern.compile(delimitersRegex);
}
final Matcher delimMatcher = delimPattern.matcher(str);
boolean delimiterFound = delimMatcher.find();
int delimeterStart = -1;
if (delimiterFound){
delimeterStart = delimMatcher.start();
}
final int strLen = str.length();
final StringBuilder buffer = new StringBuilder(strLen);
boolean capitalizeNext = true;
for (int i = 0; i < strLen; i++) {
if (delimiterFound && i == delimeterStart) {
final int endIndex = delimMatcher.end();
buffer.append( str.substring(i, endIndex) );
i = endIndex;
if( (delimiterFound = delimMatcher.find()) ){
delimeterStart = delimMatcher.start();
}
capitalizeNext = true;
} else {
final char ch = str.charAt(i);
if (capitalizeNext) {
buffer.append(Character.toTitleCase(ch));
capitalizeNext = false;
} else {
buffer.append(ch);
}
}
}
return buffer.toString();
}
Hope that Helps :)
希望有帮助:)