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)。
12 个解决方案
#1
19
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();
}
#2
15
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:
...其中input是EditText视图。在视图上设置输入类型也很有帮助,因此无论如何它都默认为标题大小写:
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
#3
10
this helps you
这有助于你
EditText view = (EditText) find..
String txt = view.getText();
txt = String.valueOf(txt.charAt(0)).toUpperCase() + txt.substring(1, txt.length());
#4
#5
6
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
#6
5
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.
希望能帮助到你。
#7
3
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();
}
#8
2
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 ARE considered "word characters" so this last version met my needs perfectly and hopefully will help someone else out there.
值得一提的是,数字和连字符被认为是“单词字符”,因此最后一个版本完全符合我的需求,并希望能帮助其他人。
#9
0
Please check the solution below it will work for both multiple string and also single string to
请检查下面的解决方案,它将适用于多个字符串和单个字符串
String toBeCapped = "i want this sentence capitalized";
String[] tokens = toBeCapped.split("\\s");
if(tokens.length>0)
{
toBeCapped = "";
for(int i = 0; i < tokens.length; i++)
{
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1, tokens[i].length());
}
}
else
{
char capLetter = Character.toUpperCase(toBeCapped.charAt(0));
toBeCapped += " " + capLetter + toBeCapped .substring(1, toBeCapped .length());
}
#10
0
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()) + " ";
}
}
#11
0
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 :)
希望有助于:)
#12
0
Use this function to convert data in camel case
使用此函数转换驼峰情况下的数据
public static String camelCase(String stringToConvert) {
if (TextUtils.isEmpty(stringToConvert))
{return "";}
return Character.toUpperCase(stringToConvert.charAt(0)) +
stringToConvert.substring(1).toLowerCase();
}
#1
19
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();
}
#2
15
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:
...其中input是EditText视图。在视图上设置输入类型也很有帮助,因此无论如何它都默认为标题大小写:
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
#3
10
this helps you
这有助于你
EditText view = (EditText) find..
String txt = view.getText();
txt = String.valueOf(txt.charAt(0)).toUpperCase() + txt.substring(1, txt.length());
#4
#5
6
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
#6
5
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.
希望能帮助到你。
#7
3
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();
}
#8
2
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 ARE considered "word characters" so this last version met my needs perfectly and hopefully will help someone else out there.
值得一提的是,数字和连字符被认为是“单词字符”,因此最后一个版本完全符合我的需求,并希望能帮助其他人。
#9
0
Please check the solution below it will work for both multiple string and also single string to
请检查下面的解决方案,它将适用于多个字符串和单个字符串
String toBeCapped = "i want this sentence capitalized";
String[] tokens = toBeCapped.split("\\s");
if(tokens.length>0)
{
toBeCapped = "";
for(int i = 0; i < tokens.length; i++)
{
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1, tokens[i].length());
}
}
else
{
char capLetter = Character.toUpperCase(toBeCapped.charAt(0));
toBeCapped += " " + capLetter + toBeCapped .substring(1, toBeCapped .length());
}
#10
0
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()) + " ";
}
}
#11
0
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 :)
希望有助于:)
#12
0
Use this function to convert data in camel case
使用此函数转换驼峰情况下的数据
public static String camelCase(String stringToConvert) {
if (TextUtils.isEmpty(stringToConvert))
{return "";}
return Character.toUpperCase(stringToConvert.charAt(0)) +
stringToConvert.substring(1).toLowerCase();
}