是否存在将字符串转换为标题大小写的方法?


99

是否有内置方法可用于将字符串转换为标题大小写格式?


3
每个人都在阅读这个问题:请注意,这里许多投票最多的答案对所有语言都无法正常工作。您需要一个支持i18n的库来正确命名标题,例如ICU4J(请参见Daniel F的答案)。
sffc

Answers:


106

Apache Commons StringUtils.capitalize()或Commons Text WordUtils.capitalize()

例如:WordUtils.capitalize("i am FINE") = "I Am FINE"来自WordUtils doc


14
WordUtils.capitalizeFully()对我来说更好,因为它给出了:WordUtils.capitalizeFully(“ i am FINE”)=“ I Am Fine”
theINtoy 2015年

2
只是一个小小的更新,WordUtils就转到了Commons Text,并在Commons Lang中弃用了
msrd0

春天也有StringUtils.capitalise()
OrangeDog

@OrangeDog是什么意思capitalize()
TylerH

@TylerH是的,自动更正了
OrangeDog

60

Java的String类中没有大写()或titleCase()方法。您有两种选择:

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

实施范例

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

1
这是一个很好的小例程,但是对于字符串可能代表名称的更一般的情况,它却失败了。在这种情况下,也需要在撇号和连字符后进行大写。例如。奥康纳和威尔克斯·布斯(J. Wilkes-Booth)。当然,其他语言可能还有其他标题大小写规则。
斯科特,

...如果要包括它,是否需要整个字典查找才能确定当前单词是否是名称?对于任何一种方法来说,这似乎都有很多。
MMJZ 2015年

此代码几乎可以正常使用,因为某些名称可以具有诸如de,del,della,dei,da之类的前置词,例如Maria del Carmen,Maria da Silva,Maria della Salute等。coderanch.com/t/35096/Programming/…
JuniorMayhé16年

这不是用撇号打破吗?例如奥布莱恩。
sproketboy

1
注意:避免的内部使用的调整char[]StringBuilder,我建议使用new StringBuilder(input.length())
利诺-投票不说谢谢

38

如果我可以提出解决方案...

以下方法基于dfa发布的方法。它进行了以下主要更改(这适合我当时需要的解决方案):它将输入字符串中的所有字符都强制转换为小写,除非它紧接在“可操作的分隔符”之前,在这种情况下,该字符被强制转换为大写。

我的例程的主要局限性在于,它假设“标题大小写”在所有语言环境中均已统一定义,并由我使用的相同大小写约定表示,因此在这方面,它比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();
}

测试值

一个字符串

马林·奥马利

约翰·威尔克斯·布斯

还有另一个STRING

输出值

弦乐

马丁·奥马利

约翰·威尔克斯·布斯

另一个弦


不适用于lj之类的连字,lj的大写为LJ,但标题为case。使用Character.toTitleCase代替。
mihi 2014年

@mihi:也不适用于其他专门规则,例如。诸如McNamara或MacDonald之类的姓氏。
斯科特,2014年

但是这些情况本质上无法解决。使用正确的大小写转换功能(首字母大写应该使用大写单词,而不是大写,按照统一的规则)可以做到(这很容易)。
mihi 2014年

这样(不会)也会导致“她的”成为“她的”吗?
allicarn 2014年

这是真的。正如您所指出的那样,这在名称字段上效果很好,但在一般散文上却不行。它甚至不能在所有名称上都很好地起作用,特别是在Vulcans(T'Pau而不是T'pau)上。
斯科特2014年




3

这是基于@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();
    }

}

给定输入:

玛丽·阿恩·奥康纳·舒斯利克

输出是

玛丽·阿恩·奥康内兹-舒斯利克


2

这是我写的将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());
}

您的答案就像一个咒语,但是,该解决方案似乎无法处理单个单词序列,也许一个if条件就足够了。
yashgarg1232

1

我知道这是较旧的,但没有简单的答案,我在编码时需要此方法,因此在这里添加了此方法,易于使用。

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

1

我遇到了这个问题,我进行了搜索,然后使用一些Java关键字制作了自己的方法,只需要将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 ();
    }
}

在这里,我没有在任何地方使用修剪方法,因为在我的情况下,我得到了适当的修剪字符串。
Parveen Sishodiya

0

你可以很好地使用

org.apache.commons.lang.WordUtils

要么

案例格式

来自Google的API。


1
添加方法和示例将很有用。
jechaviz

CaseFormat仅具有程序标识符中通常使用的格式(UpperCamel,lower-hypen,UPPER_UNDERSCORE等),并且仅支持ASCII文本。将其转换为“标题大小写”时效果不佳。
M. Justin's

0

最近,我也遇到了这个问题,不幸的是,出现了很多以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;    
}

0

转换为专有名称大小写:

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

结果:“这是一些文本”


0

使用Spring的StringUtils

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

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


0

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

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

0

该转换器将任何包含驼峰大小写,空格,数字和其他字符的字符串转换为经过清理的标题大小写。

/**
 * 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

0

在实际标题中似乎没有答案的格式:“如何找到理想的工作”,“杀死一只知更鸟”,等等,所以我做了自己的方法。最适合英语文本。

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

0

这是最简单的解决方案

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

-1

这应该工作:

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

1
这不是有效的答案,因为OP要求内置功能。另请参见注释,该注释解决了其背后隐藏的复杂性,即i18n。
马库斯

-2

将任何字符串转换为标题大小写的最简单方法是使用Google包org.apache.commons.lang.WordUtils

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

会导致这个

这将是我的榜样

我不确定为什么将其命名为“ capitalizeFully”,实际上该功能并未产生全部资本结果,但是无论如何,这就是我们需要的工具。


1
之所以命名,是capitalizeFully因为它将每个单词都大写,包括标题中应小写的单词。grammar.about.com/od/tz/g/Title-Case.htm
aij

2
Apache Commons不归Google所有。它由Apache Software Foundation维护。commons.apache.org
ATutorMe'2

-3

抱歉,我是一个初学者,所以我的编码习惯很烂!

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!"));
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.