字符串大写 – 更好的方式

什么方法的资本化更好?

矿:

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

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

表现是平等的。

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

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

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

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

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

但是,请注意它们不等同于使用toUpperCase()而另一个使用toTitleCase() 。

来自论坛post :

Titlecase <>大写
Unicode定义了三种案例映射:小写,大写和标题。 大写字母和字符序列的大写和标注之间的区别可以在复合字符中看到(即,表示两个字符的组合的单个字符)。

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

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

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

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

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

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

你有时间吗?

老实说,它们是等价的..所以对你来说效果更好的那个是更好的:)

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

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

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

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

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

从这里挑选文本。

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

🙂