我搜索了高低,但只能找到对此类问题的间接引用。在开发android应用程序时,如果您有一个用户输入的字符串,您如何将其转换为标题大小写(即,将每个单词的首字母大写)?我宁愿不导入整个库(例如 Apache 的 WordUtils)。
14 回答
/**
* Function to convert string to title case
*
* @param string - Passed string
*/
public static String toTitleCase(String string) {
// Check if String is null
if (string == null) {
return null;
}
boolean whiteSpace = true;
StringBuilder builder = new StringBuilder(string); // String builder to store string
final int builderLength = builder.length();
// Loop through builder
for (int i = 0; i < builderLength; ++i) {
char c = builder.charAt(i); // Get character at builders position
if (whiteSpace) {
// Check if character is not white space
if (!Character.isWhitespace(c)) {
// Convert to title case and leave whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
whiteSpace = false;
}
} else if (Character.isWhitespace(c)) {
whiteSpace = true; // Set character is white space
} else {
builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
}
}
return builder.toString(); // Return builders text
}
您正在寻找 Apache 的WordUtils.capitalize()
方法。
我从这里得到了一些指示: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();
...输入是一个 EditText 视图。在视图上设置输入类型也很有帮助,以便它默认为标题大小写:
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
这可以帮助你
EditText view = (EditText) find..
String txt = view.getText();
txt = String.valueOf(txt.charAt(0)).toUpperCase() + txt.substring(1, txt.length());
在 XML 中,您可以这样做:
android:inputType="textCapWords"
在此处查看其他选项的参考,例如句子大小写、所有大写字母等:
http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
这是 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;
}
希望能帮助到你。
编辑:
它具有 Apache 2.0 许可证。
@straya 在评论中指出,人们可能会在没有有效许可归属的情况下直接将此代码复制到他们的项目中,从而侵犯版权。
因此,如果您想在任何地方使用此代码,请务必包含适当的许可通知,包括您可以从上述链接获得的许可通知以及说明您对其进行了修改的附加通知文本。
我刚刚遇到了同样的问题并用这个解决了它:
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);
请注意,就我而言,我还需要删除句点。在“拆分”期间,可以在方括号之间插入任何需要替换为空格的字符。例如,以下内容最终将替换下划线、句点、逗号或空格:
String[] words = input.split("[_.,\\s]+");
当然,这可以通过“非单词字符”符号更简单地完成:
String[] words = input.split("\\W+");
值得一提的是,数字和连字符被认为是“单词字符”,所以最后一个版本完美地满足了我的需求,希望能对其他人有所帮助。
只需执行以下操作:
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();
}
使用此函数以驼峰形式转换数据
public static String camelCase(String stringToConvert) {
if (TextUtils.isEmpty(stringToConvert))
{return "";}
return Character.toUpperCase(stringToConvert.charAt(0)) +
stringToConvert.substring(1).toLowerCase();
}
Kotlin - Android - Title Case / Camel Case 函数
fun toTitleCase(str: String?): String? {
if (str == null) {
return null
}
var space = true
val builder = StringBuilder(str)
val len = builder.length
for (i in 0 until len) {
val c = builder[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()
}
或者
fun camelCase(stringToConvert: String): String {
if (TextUtils.isEmpty(stringToConvert)) {
return "";
}
return Character.toUpperCase(stringToConvert[0]) +
stringToConvert.substring(1).toLowerCase();
}
请检查下面的解决方案,它适用于多个字符串和单个字符串
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());
}
我简化了@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 "";
}
}
处理空字符串(句子中有多个空格)和字符串中的单字母单词。
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()) + " ";
}
}
我基于 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();
}
希望有帮助:)
如果您正在寻找标题大小写格式,这个 kotlin 扩展功能可能会对您有所帮助。
fun String.toTitleCase(): String {
if (isNotEmpty()) {
val charArray = this.toCharArray()
return buildString {
for (i: Int in charArray.indices) {
val c = charArray[i]
// start find space from 1 because it can cause invalid index of position if (-1)
val previous = if (i > 0) charArray[(i - 1)] else null
// true if before is space char
val isBeforeSpace = previous?.let { Character.isSpaceChar(it) } ?: false
// append char to uppercase if current index is 0 or before is space
if (i == 0 || isBeforeSpace) append(c.toUpperCase()) else append(c)
print("char:$c, \ncharIndex: $i, \nisBeforeSpace: $isBeforeSpace\n\n")
}
print("result: $this")
}
} return this }
并像这样实施
data class User(val name :String){ val displayName: String get() = name.toTitleCase() }