【问题标题】:String capitalize - better way字符串大写 - 更好的方法
【发布时间】:2010-12-04 21:50:21
【问题描述】:

什么方法比较好?

我的:

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

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

【问题讨论】:

  • 反问:字符串大写真的是应用程序的瓶颈吗?
  • 我知道这并不重要,但如果我要编写任何库,我会尽量让它表现得尽可能好。
  • 有趣。如果 会写一个库,我会尽量让它工作 尽可能好。
  • codinghorror.com/blog/archives/001218.html 配置文件,然后优化。如果您正在编写一个库,请使其易于使用,难以滥用,然后担心速度。只要你不使用愚蠢的算法,它就会运行得很好。
  • 用 Kent Beck 的话来说——“让它发挥作用,让它变得正确,让它变得更快”。无论如何,开发人员通常都猜错了他们的瓶颈。

标签: java performance string optimization memory-management


【解决方案1】:

你都计时了吗?

老实说,它们是等价的。所以对表现更好的就是更好的:)

【讨论】:

【解决方案2】:

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

【讨论】:

    【解决方案3】:

    我猜你的版本会更好一点,因为它没有分配那么多的临时 String 对象。

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

    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, LATIN 大写字母 DZ。 (这是
    基本上是“DZ”。)但它的标题是 转字符 U+01F2,拉丁文大写
    带有小写字母 Z 的字母 D。(其中 我们可以写成“Dz”。)

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

    【讨论】:

    • 能否提供更多关于 toUpperCase() 和 toTitleCase() 之间区别的详细信息?
    • Apache 代码可能是为 1.4 或更早版本编写的。在 Sun 的实现中,Apache 代码不会创建任何临时的 char[] 数组(String.substring 和(最初)StringBuffer.toString 共享支持数组)。因此,在 2004 年之前,Apache 代码对于大字符串来说会更快。
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

        性能相同。

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

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

        【讨论】:

          【解决方案7】:

          看看这个问题titlecase-conversion。 Apache FTW。

          【讨论】:

            【解决方案8】:

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

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

            【讨论】:

              【解决方案9】:

              使用此方法对字符串进行大写。它完全没有任何错误

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

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

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

                  :-)

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2022-11-05
                    • 2012-05-31
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多