Java 字符串大写-更好的方法

Java 字符串大写-更好的方法,java,performance,string,optimization,memory-management,Java,Performance,String,Optimization,Memory Management,哪种资本化方法更好 地雷: 或 commons lang-StringUtils.capitalize: return new StringBuffer(strLen) .append(Character.toTitleCase(str.charAt(0))) .append(str.substring(1)) .toString(); 我想我的好一些,但我还是想问一下。你们两个都计时了吗 老实说,它们是等价的。。因此,对您

哪种资本化方法更好

地雷:

commons lang-StringUtils.capitalize:

return new StringBuffer(strLen)
            .append(Character.toTitleCase(str.charAt(0)))
            .append(str.substring(1))
            .toString();
我想我的好一些,但我还是想问一下。

你们两个都计时了吗


老实说,它们是等价的。。因此,对您来说性能更好的是:)

StringBuffer
被声明为线程安全的,因此使用它的效率可能会更低(但在实际进行一些实际测试之前,不应该对它下赌注)。

我想您的版本性能会更高一点,因为它没有分配那么多的临时字符串对象

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

但是,请注意,它们并不等同于其中一种用途和另一种用途

从a:

标题大写字母
统一码 定义三种案例映射: 小写、大写和标题。 上套管与下套管的区别 为一个或多个字符加标题 序列可以在化合物中看到 字符(即单个 表示一个组成部分的字符 两个字符)

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


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

我不知道这是否“更好”(我想你是说更快)。为什么不分析这两种解决方案呢?

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

性能相同

您的代码复制char[]调用
string.tocharray()
新字符串(charArray)


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

看看这个问题。ApacheFTW。

如果我要编写一个库,我会尽量确保我的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);

(在提交之前,我可能还会查找title和大写之间的差异。)

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

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;
}
公共字符串大写字符串(字符串值)
{
字符串=值;
字符串大写“”;
System.out.println(字符串);
对于(int i=0;i
如果只大写有限的单词,最好将其缓存

@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));
}
@测试
公共无效测试用例()
{
String all=“基本上,shell只是一个执行命令的宏处理器。术语“宏处理器”指的是扩展文本和符号以创建更大表达式的功能。\n”+
“\n”+
Unix shell既是命令解释器又是编程语言。作为命令解释器,shell为丰富的GNU实用程序集提供用户界面。编程语言功能允许将这些实用程序组合在一起。可以创建包含命令的文件,并将其自身变为命令。这些新命令具有相同的功能状态为/bin等目录中的系统命令,允许用户或组建立自定义环境以自动执行其常见任务。\n+
“\n”+
Shell可以交互或非交互使用。在交互模式下,Shell接受从键盘键入的输入。在非交互执行时,Shell执行从文件读取的命令。\n+
“\n”+
shell允许同步和异步执行GNU命令。shell在接受更多输入之前等待同步命令完成;异步命令在读取和执行其他命令时继续与shell并行执行。重定向构造允许对输入进行细粒度控制和这些命令的输出。此外,shell允许控制命令环境的内容。\n“+
“\n”+
“Shell还提供一小组内置命令(内置命令)通过单独的实用程序实现不可能或不方便获得的功能。例如,cd、break、continue和exec不能在shell之外实现,因为它们直接操作shell本身。历史记录、getopts、kill或pwd内置项等可以在单独的实用程序中实现,但它们更容易协同工作易于用作内置命令。所有shell内置命令将在后续章节中介绍。\n“+
“\n”+
虽然执行命令是必不可少的,但shell的大部分功能(和复杂性)都是由于其嵌入式编程语言。与任何高级语言一样,shell提供变量、流控制结构、引用和函数。\n+
“\n”+
“Shell提供的功能专门用于交互使用,而不是扩充编程语言。这些交互功能包括作业控制、命令行编辑、命令历史记录和别名。这些功能中的每一个都是descr
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);
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;
}
/**
     * 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);
        }
    }
@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));
}