代码之家  ›  专栏  ›  技术社区  ›  IAdapter

字符串大写-更好的方法

  •  8
  • IAdapter  · 技术社区  · 15 年前

    地雷:

    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 回复  |  直到 15 年前
        1
  •  8
  •   Lucero    15 年前

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

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

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

    但是,请注意,它们并不等同于我们所使用的 toUpperCase() 还有其他用途 toTitleCase() .

    forum post :

    滴定酶<&燃气轮机;大写字母
    统一码 小写、大写和标题。 上套管与下套管的区别 为一个或多个字符加标题 序列可以在化合物中看到 表示一个组成部分的字符 两个字符)。

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

    character uppercase titlecase
    --------- --------- ---------
    dz        DZ        Dz
    
        2
  •  3
  •   Tom Hawtin - tackline    15 年前

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

        3
  •  2
  •   Thomas Jung    15 年前

    表现是平等的。

    您的代码复制了调用 string.toCharArray() new String(charArray) .

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

        4
  •  1
  •   Grzegorz Oledzki    15 年前

    StringBuffer 被声明为线程安全的,因此使用它可能不太有效(但在实际执行一些实际测试之前,不应该打赌它)。

        5
  •  1
  •   Chris R    15 年前

        6
  •  0
  •   warren    15 年前

    你两个都计时了吗?

    老实说,它们是等价的。。因此,一个表现更好的 是更好的:)

        7
  •  0
  •   mxk    15 年前

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

        8
  •  0
  •   Community Romance    7 年前
        9
  •  0
  •   user2326591    11 年前

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

    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;
    }
    
        10
  •  0
  •   ahmed_khan_89    10 年前
    /**
         * 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);
            }
        }
    
        11
  •  0
  •   wener    9 年前

    如果只大写有限的单词,最好将其缓存。

    @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进行缓存会更好。

    :-)