有没有一种方法可以将字符串转换为标题格?

是否有任何内置的方法可用于将字符串转换为 Title Case 格式?

147155 次浏览

Java 的 String 类中没有大写()或 titleCase ()方法:

 StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
  • 写(另一个)静态助手方法 toTitleCase ()

示例实现

public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
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();
}

测试箱

    System.out.println(toTitleCase("string"));
System.out.println(toTitleCase("another string"));
System.out.println(toTitleCase("YET ANOTHER STRING"));

产出:

String
Another String
YET ANOTHER STRING

Apache Commons 大写()或 Commons Text 大写()

例如: WordUtils文件中的 WordUtils.capitalize("i am FINE") = "I Am FINE"

请允许我提出我对解决方案的看法。

下面的方法基于 dfa 发布的方法。它进行了以下主要更改(这适合我当时需要的解决方案) : 它强制输入字符串中的所有字符都变成小写,除非它的前面立即加上一个“可操作的分隔符”,在这种情况下,字符被强制变成大写。

我的例程的一个主要限制是,它假设“ title case”是为所有语言环境统一定义的,并且由我使用过的相同的 case 约定表示,因此在这方面它没有 dfa 的代码有用。

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();
}

测试值

一根绳子

马丁・奥马利

John Wilkes-Booth

YET ANOTHER STRING

输出

字符串

马丁 · 奥马利

John Wilkes-Booth

又一根弦

使用 Apache Commons 中的 CapitalizeFull ()

WordUtils.capitalizeFully(null)        = null
WordUtils.capitalizeFully("")          = ""
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"

对不起,我是一个初学者,所以我的编程习惯糟透了!

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!"));
}
}

将任何字符串转换为 title case 的最简单方法是使用 google 包 org.apache.comms.lang.WordUtils

System.out.println(WordUtils.capitalizeFully("tHis will BE MY EXAMple"));

会导致这种结果

这就是我的例子

我不知道为什么它被命名为“ CapitalizeFull”,实际上这个函数并没有得到完整的大写结果,但无论如何,这就是我们需要的工具。

您可以像下面这样使用 apache commons lang:

WordUtils.capitalizeFully("this is a text to be capitalize")

你可以在这里找到 java 文档: 完整的 java 文档

如果你想移除两个世界之间的空格,你可以使用:

StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize")," ")

you can find the java doc for String StringUtils.remove java doc

希望这个能帮上忙。

我知道这是旧的一个,但没有携带简单的答案,我需要这个方法为我的编码,所以我在这里添加,简单易用。

public static String toTitleCase(String input) {
input = input.toLowerCase();
char c =  input.charAt(0);
String s = new String("" + c);
String f = s.toUpperCase();
return f + input.substring(1);
}

你可以很好地利用

Org.apache.commans.lang WordUtils

或者

个案格式

来自谷歌的 API。

这是我编写的用于将 Snake _ case 转换为 lowerCamelCase 的代码,但是可以根据需求轻松地进行调整

private String convertToLowerCamel(String startingText)
{
String[] parts = startingText.split("_");
return parts[0].toLowerCase() + Arrays.stream(parts)
.skip(1)
.map(part -> part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
.collect(Collectors.joining());
}

如果希望根据最新的 Unicode 标准得到正确答案,应该使用 icu4j。

UCharacter.toTitleCase(Locale.US, "hello world", null, 0);

请注意,这是区域设置敏感的。

Api 文件

Implementation

下面是另一个基于@dfa 和@scottb 的答案,它可以处理任何非字母/数字字符:

public final class TitleCase {


public static String toTitleCase(String input) {


StringBuilder titleCase = new StringBuilder(input.length());
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 Annn O’Conne-USLIK

输出是

Mary Annn O’Conne-uslik

我最近也遇到了这个问题,不幸的是,很多名字都是从 Mc 和 Mac 开始的,我最终使用了一个 Scottb 的代码版本,我修改了它来处理这些前缀,所以它就在这里,以防有人想要使用它。

仍然有边缘情况下,这是错过了,但最坏的事情可能发生的是,一个字母将是小写时,它应该大写。

/**
* Get a nicely formatted representation of the name.
* Don't send this the whole name at once, instead send it the components.<br>
* For example: andrew macnamara would be returned as:<br>
* Andrew Macnamara if processed as a single string<br>
* 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;
}

转换为正式名称的情况:

String s= "ThiS iS SomE Text";
String[] arr = s.split(" ");
s = "";
for (String s1 : arr) {
s += WordUtils.capitalize(s1.toLowerCase()) + " ";
}
s = s.substring(0, s.length() - 1);

结果: “这是一些文本”

此转换器将包含驼峰大小写、空白、数字和其他字符的任何字符串转换为经过消毒的标题大小写。

/**
* Convert a string to title case in java (with tests).
*
* @author Sudipto Chandra
*/
public abstract class TitleCase {


/**
* Returns the character type. <br>
* <br>
* Digit = 2 <br>
* Lower case alphabet = 0 <br>
* Uppercase case alphabet = 1 <br>
* 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.
* <br>
* 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.
* <br>
* 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\n", 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\n", 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\n", 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\n", 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\n", 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'\nWANTS '%s'\nFOUND '%s'\n", 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("\n%d Passed, %d Failed.\n", pass, samples.length - pass);
}


public static void main(String[] args) {
// run tests
testTitleCase();
}
}

以下是一些投入:

aCamel
TitleCase
snake_case
fromCamelCASEString
ABCTest
expect11
_paren-_-allow--not!
why_underScore   exists
last one onTheList

我的成果是:

A Camel
Title Case
Snake Case
From Camel Case String
Abc Test
Expect11
Paren Allow Not
Why Under Score Exists
Last One On The List

使用 Spring 的 StringUtils:

org.springframework.util.StringUtils.capitalize(someText);

如果您已经在使用 Spring,那么这就避免了引入另一个框架。

This should work:

String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
Character oldchar=str1.charAt(0);
Character newchar=Character.toUpperCase(str1.charAt(0));
strNew=strNew+str1.replace(oldchar,newchar)+" ";
}
System.out.println(strNew);

使用此方法将字符串转换为标题大小写:

static String toTitleCase(String word) {
return Stream.of(word.split(" "))
.map(w -> w.toUpperCase().charAt(0)+ w.toLowerCase().substring(1))
.reduce((s, s2) -> s + " " + s2).orElse("");
}

我有这个问题,我寻找它 then i made my own method using some java keywords 只需要将 String 变量作为参数传递,并将输出作为正确的标题 String。

public class Main
{
public static void main (String[]args)
{
String st = "pARVeEN sISHOsIYA";
String mainn = getTitleCase (st);
System.out.println (mainn);
}




public static String getTitleCase(String input)
{
StringBuilder titleCase = new StringBuilder (input.length());
boolean hadSpace = false;
for (char c:input.toCharArray ()){
if(Character.isSpaceChar(c)){
hadSpace = true;
titleCase.append (c);
continue;
}
if(hadSpace){
hadSpace = false;
c = Character.toUpperCase(c);
titleCase.append (c);
}else{
c = Character.toLowerCase(c);
titleCase.append (c);
}
}
String temp=titleCase.toString ();
StringBuilder titleCase1 = new StringBuilder (temp.length ());
int num=1;
for (char c:temp.toCharArray ())
{   if(num==1)
c = Character.toUpperCase(c);
titleCase1.append (c);
num=0;
}
return titleCase1.toString ();
}
}

似乎没有一个答案可以用实际的标题格式来表示: “如何找到你梦寐以求的工作”、“杀死一只反舌鸟”等等,所以我自己制定了一个方法。最适合英语文本。

private final static Set<Character> TITLE_CASE_DELIMITERS = new HashSet<>();


static {
TITLE_CASE_DELIMITERS.add(' ');
TITLE_CASE_DELIMITERS.add('.');
TITLE_CASE_DELIMITERS.add(',');
TITLE_CASE_DELIMITERS.add(';');
TITLE_CASE_DELIMITERS.add('/');
TITLE_CASE_DELIMITERS.add('-');
TITLE_CASE_DELIMITERS.add('(');
TITLE_CASE_DELIMITERS.add(')');
}


private final static Set<String> TITLE_SMALLCASED_WORDS = new HashSet<>();


static {
TITLE_SMALLCASED_WORDS.add("a");
TITLE_SMALLCASED_WORDS.add("an");
TITLE_SMALLCASED_WORDS.add("the");
TITLE_SMALLCASED_WORDS.add("for");
TITLE_SMALLCASED_WORDS.add("in");
TITLE_SMALLCASED_WORDS.add("on");
TITLE_SMALLCASED_WORDS.add("of");
TITLE_SMALLCASED_WORDS.add("and");
TITLE_SMALLCASED_WORDS.add("but");
TITLE_SMALLCASED_WORDS.add("or");
TITLE_SMALLCASED_WORDS.add("nor");
TITLE_SMALLCASED_WORDS.add("to");
}


public static String toCapitalizedWord(String oneWord) {
if (oneWord.length() < 1) {
return oneWord.toUpperCase();
}
return "" + Character.toTitleCase(oneWord.charAt(0)) + oneWord.substring(1).toLowerCase();
}


public static String toTitledWord(String oneWord) {
if (TITLE_SMALLCASED_WORDS.contains(oneWord.toLowerCase())) {
return oneWord.toLowerCase();
}
return toCapitalizedWord(oneWord);
}


public static String toTitleCase(String str) {
StringBuilder result = new StringBuilder();
StringBuilder oneWord = new StringBuilder();


char previousDelimiter = 'x';
/* on start, always move to upper case */
for (char c : str.toCharArray()) {
if (TITLE_CASE_DELIMITERS.contains(c)) {
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
oneWord.setLength(0);
result.append(c);
previousDelimiter = c;
} else {
oneWord.append(c);
}
}
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
return result.toString();
}


public static void main(String[] args) {
System.out.println(toTitleCase("one year in paris"));
System.out.println(toTitleCase("How to Land Your Dream Job"));
}

这是最简单的解决方案

    static void title(String a,String b){
String ra = Character.toString(Character.toUpperCase(a.charAt(0)));
String rb = Character.toString(Character.toUpperCase(b.charAt(0)));
for(int i=1;i<a.length();i++){
ra+=a.charAt(i);
}
for(int i=1;i<b.length();i++){
rb+=b.charAt(i);
}
System.out.println(ra+" "+rb);