字符串大写 - 更好的方式

时间:2009-10-08 07:59:28

标签: java performance string optimization memory-management

哪种资本化方法更好?

矿:

char[] charArray = string.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
return new String(charArray);

commons lang - StringUtils.capitalize:

return new StringBuffer(strLen)
            .append(Character.toTitleCase(str.charAt(0)))
            .append(str.substring(1))
            .toString();

我认为我的更好,但我宁愿问。

11 个答案:

答案 0 :(得分:8)

我猜你的版本会有更高的性能,因为它没有分配尽可能多的临时String对象。

我会这样做(假设字符串不为空):

StringBuilder strBuilder = new StringBuilder(string);
strBuilder.setCharAt(0, Character.toUpperCase(strBuilder.charAt(0))));
return strBuilder.toString();

但请注意,它们不相同,因为它使用toUpperCase()而另一个使用toTitleCase()

来自forum post

  

Titlecase<>大写
    统一   定义了三种案例映射:   小写,大写和标题。   大写和   标记角色或角色   序列可以在化合物中看到   字符(即单个字符   代表compount的字符   两个字符)。

     

例如,在Unicode中,字符   U + 01F3是LATIN SMALL LETTER DZ。 (让   我们写这个复合字符   使用ASCII作为“dz”。)此字符
  大写字母U + 01F1,LATIN   大写字母DZ。 (这是   基本上是“DZ”。)但它标题为   字符U + 01F2,LATIN CAPITAL
  带有小写字母的字母D.(其中   我们可以写“Dz”。)

character uppercase titlecase
--------- --------- ---------
dz        DZ        Dz

答案 1 :(得分:3)

如果我要写一个库,我会尽量确保我的Unicode正确地担心性能。在我的头顶:

int len = str.length();
if (len == 0) {
    return str;
}
int head = Character.toUpperCase(str.codePointAt(0));
String tail = str.substring(str.offsetByCodePoints(0, 1));
return new String(new int[] { head }).concat(tail);

(在我提交之前,我可能也会查看标题和大写之间的区别。)

答案 2 :(得分:2)

表现平等。

您的代码会复制char [],呼叫string.toCharArray()new String(charArray)

buffer.append(str.substring(1))buffer.toString()上的apache代码。 apache代码有一个额外的字符串实例,它具有基本的char [1,length]内容。但是在创建实例String时不会复制它。

答案 3 :(得分:1)

声明

StringBuffer是线程安全的,因此使用它可能效率较低(但实际做一些实际测试之前不应该赌它)。

答案 4 :(得分:1)

StringBuilder(从Java 5开始)比StringBuffer快,如果你不需要它是线程安全的,但正如其他人所说,你需要测试这是否比你的解决方案更好。

答案 5 :(得分:0)

你有时间吗?

老实说,它们是等价的......所以对于 表现更好的那个是更好的一个:)

答案 6 :(得分:0)

不确定toUpperCase和toTitleCase之间的区别是什么,但看起来你的解决方案需要少一个String类的实例化,而commons lang实现需要两个(substring和toString创建新的字符串我假设,因为String是不可变的)。

这是否“更好”(我猜你的意思更快)我不知道。你为什么不描述这两种解决方案?

答案 7 :(得分:0)

看看这个问题titlecase-conversion。阿帕奇FTW。

答案 8 :(得分:0)

使用此方法来大写字符串。它没有任何错误完全正常工作

public String capitalizeString(String value)
{
    String string = value;
    String capitalizedString = "";
    System.out.println(string);
    for(int i = 0; i < string.length(); i++)
    {
        char ch = string.charAt(i);
        if(i == 0 || string.charAt(i-1)==' ')
            ch = Character.toUpperCase(ch);
        capitalizedString += ch;
    }
    return capitalizedString;
}

答案 9 :(得分:0)

/**
     * capitalize the first letter of a string
     * 
     * @param String
     * @return String
     * */
    public static String capitalizeFirst(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

答案 10 :(得分:0)

如果您只使用有限的单词,则最好将其缓存。

@Test
public void testCase()
{
    String all = "At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions.\n" +
            "\n" +
            "A Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNU utilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users or groups to establish custom environments to automate their common tasks.\n" +
            "\n" +
            "Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file.\n" +
            "\n" +
            "A shell allows execution of GNU commands, both synchronously and asynchronously. The shell waits for synchronous commands to complete before accepting more input; asynchronous commands continue to execute in parallel with the shell while it reads and executes additional commands. The redirection constructs permit fine-grained control of the input and output of those commands. Moreover, the shell allows control over the contents of commands’ environments.\n" +
            "\n" +
            "Shells also provide a small set of built-in commands (builtins) implementing functionality impossible or inconvenient to obtain via separate utilities. For example, cd, break, continue, and exec cannot be implemented outside of the shell because they directly manipulate the shell itself. The history, getopts, kill, or pwd builtins, among others, could be implemented in separate utilities, but they are more convenient to use as builtin commands. All of the shell builtins are described in subsequent sections.\n" +
            "\n" +
            "While executing commands is essential, most of the power (and complexity) of shells is due to their embedded programming languages. Like any high-level language, the shell provides variables, flow control constructs, quoting, and functions.\n" +
            "\n" +
            "Shells offer features geared specifically for interactive use rather than to augment the programming language. These interactive features include job control, command line editing, command history and aliases. Each of these features is described in this manual.";
    String[] split = all.split("[\\W]");

    // 10000000
    // upper Used 606
    // hash Used 114

    // 100000000
    // upper Used 5765
    // hash Used 1101

    HashMap<String, String> cache = Maps.newHashMap();

    long start = System.currentTimeMillis();
    for (int i = 0; i < 100000000; i++)
    {

        String upper = split[i % split.length].toUpperCase();

//            String s = split[i % split.length];
//            String upper = cache.get(s);
//            if (upper == null)
//            {
//                cache.put(s, upper = s.toUpperCase());
// 
//            }
    }
    System.out.println("Used " + (System.currentTimeMillis() - start));
}

该文字来自here

目前,我需要大写表名和列,多次,但它们是有限的。使用hashMap缓存会更好。

: - )