String conversion to Title Case
是否有内置方法可以将字符串转换为标题大小写格式?
apache commons stringutils.capitalize()或wordutils.capitalize()。
例如:
字符串类中没有capitalize()或titleCase()方法。您有两个选择:
- 使用commons lang字符串实用程序。
1 2 3 4 5 | StringUtils.capitalize(null) = null StringUtils.capitalize("") ="" StringUtils.capitalize("cat") ="Cat" StringUtils.capitalize("cAt") ="CAt" StringUtils.capitalize("'cat'") ="'cat'" |
- 将(又一个)静态帮助器方法写入itlecase()。
示例实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static String toTitleCase(String input) { StringBuilder titleCase = new StringBuilder(input.lenght()); boolean nextTitleCase = true; for (char c : input.toCharArray()) { if (Character.isSpaceChar(c)) { nextTitleCase = true; } else if (nextTitleCase) { c = Character.toTitleCase(c); nextTitleCase = false; } titleCase.append(c); } return titleCase.toString(); } |
测试向量
1 2 3 |
输出:
如果我可以提交我的解决方案…
以下方法基于DFA发布的方法。它进行了以下主要更改(这适用于我当时需要的解决方案):它强制输入字符串中的所有字符使用小写,除非它前面紧接着一个"可操作分隔符",在这种情况下,字符将强制使用大写。
我的程序的一个主要限制是,它假设"标题大小写"是为所有地区统一定义的,并且由我使用的相同大小写约定表示,因此在这方面它不如DFA的代码有用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static String toDisplayCase(String s) { final String ACTIONABLE_DELIMITERS =" '-/"; // these cause the character following // to be capitalized StringBuilder sb = new StringBuilder(); boolean capNext = true; for (char c : s.toCharArray()) { c = (capNext) ? Character.toUpperCase(c) : Character.toLowerCase(c); sb.append(c); capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed } return sb.toString(); } |
测试值
a string
maRTin o'maLLEY
john wilkes-booth
YET ANOTHER STRING
输出
a string
maRTin o'maLLEY
john wilkes-booth
YET ANOTHER STRING
使用ApacheCommons中的wordUtils.capitalizefully()。
1 2 3 | WordUtils.capitalizeFully(null) = null WordUtils.capitalizeFully("") ="" WordUtils.capitalizeFully("i am FINE") ="I Am Fine" |
您可以这样使用Apache Commons语言:
1 | WordUtils.capitalizeFully("this is a text to be capitalize") |
您可以在这里找到Java文档:WordDuff.Basic的Java文档
如果你想删除世界之间的空间,你可以使用:
1 | StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize"),"") |
您可以找到字符串的Java doc删除Java文档
希望能帮上忙。
如果你想根据最新的Unicode标准得到正确的答案,你应该使用ICU4J。
1 |
请注意,这是区域设置敏感的。
API文档
实施
我写这篇文章是为了将Snake_案例转换为Lowercamelcase,但可以根据需要轻松地进行调整。
1 2 3 4 5 6 7 8 |
下面是另一个基于@dfa和@scottb答案的处理任何非字母/数字字符的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public final class TitleCase { public static String toTitleCase(String input) { StringBuilder titleCase = new StringBuilder(); boolean nextTitleCase = true; for (char c : input.toLowerCase().toCharArray()) { if (!Character.isLetterOrDigit(c)) { nextTitleCase = true; } else if (nextTitleCase) { c = Character.toTitleCase(c); nextTitleCase = false; } titleCase.append(c); } return titleCase.toString(); } } |
给定输入:
MARY ?NN O’CONNE?-?USLIK
输出为
MARY ?NN O’CONNE?-?USLIK
我知道这是旧的,但没有简单的答案,我需要这个方法来编码,所以我在这里添加了一个简单易用的方法。
1 2 3 4 5 6 7 |
使用此方法将字符串转换为标题大小写:
1 2 3 4 5 |
我最近也遇到了这个问题,不幸的是,有很多以mc和mac开头的名字出现,最后我使用了scottb代码的一个版本,我更改了这个版本来处理这些前缀,所以它就在这里,以防有人想使用它。
仍然有一些边缘的情况,这错过了,但最糟糕的是,一封信将是小写时,它应该大写。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /** * Get a nicely formatted representation of the name. * Don't send this the whole name at once, instead send it the components. * For example: andrew macnamara would be returned as: * Andrew Macnamara if processed as a single string * Andrew MacNamara if processed as 2 strings. * @param name * @return correctly formatted name */ public static String getNameTitleCase (String name) { final String ACTIONABLE_DELIMITERS =" '-/"; StringBuilder sb = new StringBuilder(); if (name !=null && !name.isEmpty()){ boolean capitaliseNext = true; for (char c : name.toCharArray()) { c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c); sb.append(c); capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); } name = sb.toString(); if (name.startsWith("Mc") && name.length() > 2 ) { char c = name.charAt(2); if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) { sb = new StringBuilder(); sb.append (name.substring(0,2)); sb.append (name.substring(2,3).toUpperCase()); sb.append (name.substring(3)); name=sb.toString(); } } else if (name.startsWith("Mac") && name.length() > 3) { char c = name.charAt(3); if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) { sb = new StringBuilder(); sb.append (name.substring(0,3)); sb.append (name.substring(3,4).toUpperCase()); sb.append (name.substring(4)); name=sb.toString(); } } } return name; } |
转换为正确的标题大小写:
1 2 3 4 5 6 7 |
结果:"这是一些文本"
我需要一个标题大小写转换器来转换任何包含驼色大小写、空格、数字和其他字符的字符串。但所有可用的解决方案都不起作用。最后,我自己做了一个。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | /* * Copyright (C) 2018 Sudipto Chandra * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Convert a string to title case in java (with tests). * * @author Sudipto Chandra */ public abstract class TitleCase { /** * Returns the character type. * * Digit = 2 * Lower case alphabet = 0 * Uppercase case alphabet = 1 * All else = -1. * * @param ch * @return */ private static int getCharType(char ch) { if (Character.isLowerCase(ch)) { return 0; } else if (Character.isUpperCase(ch)) { return 1; } else if (Character.isDigit(ch)) { return 2; } return -1; } /** * Converts any given string in camel or snake case to title case. * * It uses the method getCharType and ignore any character that falls in * negative character type category. It separates two alphabets of not-equal * cases with a space. It accepts numbers and append it to the currently * running group, and puts a space at the end. * * If the result is empty after the operations, original string is returned. * * @param text the text to be converted. * @return a title cased string */ public static String titleCase(String text) { if (text == null || text.length() == 0) { return text; } char[] str = text.toCharArray(); StringBuilder sb = new StringBuilder(); boolean capRepeated = false; for (int i = 0, prev = -1, next; i < str.length; ++i, prev = next) { next = getCharType(str[i]); // trace consecutive capital cases if (prev == 1 && next == 1) { capRepeated = true; } else if (next != 0) { capRepeated = false; } // next is ignorable if (next == -1) { // System.out.printf("case 0, %d %d %s ", prev, next, sb.toString()); continue; // does not append anything } // prev and next are of same type if (prev == next) { sb.append(str[i]); // System.out.printf("case 1, %d %d %s ", prev, next, sb.toString()); continue; } // next is not an alphabet if (next == 2) { sb.append(str[i]); // System.out.printf("case 2, %d %d %s ", prev, next, sb.toString()); continue; } // next is an alphabet, prev was not + // next is uppercase and prev was lowercase if (prev == -1 || prev == 2 || prev == 0) { if (sb.length() != 0) { sb.append(' '); } sb.append(Character.toUpperCase(str[i])); // System.out.printf("case 3, %d %d %s ", prev, next, sb.toString()); continue; } // next is lowercase and prev was uppercase if (prev == 1) { if (capRepeated) { sb.insert(sb.length() - 1, ' '); capRepeated = false; } sb.append(str[i]); // System.out.printf("case 4, %d %d %s ", prev, next, sb.toString()); } } String output = sb.toString().trim(); output = (output.length() == 0) ? text : output; //return output; // Capitalize all words (Optional) String[] result = output.split(""); for (int i = 0; i < result.length; ++i) { result[i] = result[i].charAt(0) + result[i].substring(1).toLowerCase(); } output = String.join("", result); return output; } /** * Test method for the titleCase() function. */ public static void testTitleCase() { System.out.println("--------------- Title Case Tests --------------------"); String[][] samples = { {null, null}, {"",""}, {"a","A"}, {"aa","Aa"}, {"aaa","Aaa"}, {"aC","A C"}, {"AC","Ac"}, {"aCa","A Ca"}, {"ACa","A Ca"}, {"aCamel","A Camel"}, {"anCamel","An Camel"}, {"CamelCase","Camel Case"}, {"camelCase","Camel Case"}, {"snake_case","Snake Case"}, {"toCamelCaseString","To Camel Case String"}, {"toCAMELCase","To Camel Case"}, {"_under_the_scoreCamelWith_","Under The Score Camel With"}, {"ABDTest","Abd Test"}, {"title123Case","Title123 Case"}, {"expect11","Expect11"}, {"all0verMe3","All0 Ver Me3"}, {"___","___"}, {"__a__","A"}, {"_A_b_c____aa","A B C Aa"}, {"_get$It132done","Get It132 Done"}, {"_122_","122"}, {"_no112","No112"}, {"Case-13title","Case13 Title"}, {"-no-allow-","No Allow"}, {"_paren-_-allow--not!","Paren Allow Not"}, {"Other.Allow.--False?","Other Allow False"}, {"$39$ldl%LK3$lk_389$klnsl-32489 3 42034","39 Ldl Lk3 Lk389 Klnsl32489342034"}, {"tHis will BE MY EXAMple","T His Will Be My Exa Mple"}, {"stripEvery.damn-paren- -_now","Strip Every Damn Paren Now"}, {"getMe","Get Me"}, {"whatSthePoint","What Sthe Point"}, {"n0pe_aLoud","N0 Pe A Loud"}, {"canHave SpacesThere","Can Have Spaces There"}, {" why_underScore exists ","Why Under Score Exists"}, {"small-to-be-seen","Small To Be Seen"}, {"toCAMELCase","To Camel Case"}, {"_under_the_scoreCamelWith_","Under The Score Camel With"}, {"last one onTheList","Last One On The List"} }; int pass = 0; for (String[] inp : samples) { String out = titleCase(inp[0]); //String out = WordUtils.capitalizeFully(inp[0]); System.out.printf("TEST '%s' WANTS '%s' FOUND '%s' ", inp[0], inp[1], out); boolean passed = (out == null ? inp[1] == null : out.equals(inp[1])); pass += passed ? 1 : 0; System.out.println(passed ?"-- PASS --" :"!! FAIL !!"); System.out.println(); } System.out.printf(" %d Passed, %d Failed. ", pass, samples.length - pass); } public static void main(String[] args) { // run tests testTitleCase(); } } |
以下是一些输入:
1 2 3 4 5 6 7 8 9 | aCamel TitleCase snake_case fromCamelCASEString ABCTest expect11 _paren-_-allow--not! why_underScore exists last one onTheList |
我的输出:
1 2 3 4 5 6 7 8 9 |
使用弹簧:
1 | org.springframework.util.StringUtils.capitalize(someText); |
如果您已经在使用Spring,这就避免了引入另一个框架。
你可以很好地使用
org.apache.commons.lang.WordUtils
或
CaseFormat
来自谷歌的API。
这应该有效:
1 2 3 4 5 6 7 8 9 10 |
将任何字符串转换为标题大小写的最简单方法是使用googles包org.apache.commons.lang.wordutils
1 |
会导致这个
This Will Be My Example
我不知道为什么它被命名为"资本化",实际上函数并没有做一个完整的资本结果,但无论如何,这是我们需要的工具。
对不起,我是初学者,所以我的编码习惯很糟糕!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class TitleCase { String title(String sent) { sent =sent.trim(); sent = sent.toLowerCase(); String[] str1=new String[sent.length()]; for(int k=0;k<=str1.length-1;k++){ str1[k]=sent.charAt(k)+""; } for(int i=0;i<=sent.length()-1;i++){ if(i==0){ String s= sent.charAt(i)+""; str1[i]=s.toUpperCase(); } if(str1[i].equals("")){ String s= sent.charAt(i+1)+""; str1[i+1]=s.toUpperCase(); } System.out.print(str1[i]); } return""; } public static void main(String[] args) { TitleCase a = new TitleCase(); System.out.println(a.title(" enter your Statement!")); } } |