[英]Capitalizing first char in every word in a String in java (but ignoring specific word)
Can anyone please tell me why the following code prints 1 the high street and not 1 The High Street?: 任何人都可以告诉我为什么下面的代码打印1高街而不是1高街?
String propertyPageTitle = "1-the-high-street";
propertyPageTitle = propertyPageTitle.replace("-", " ");
WordUtils.capitalizeFully(propertyPageTitle);
System.out.println(propertyPageTitle);
EDIT to show solution: 编辑以显示解决方案:
String propertyPageTitle = "1-the-high-street";
propertyPageTitle = propertyPageTitle.replace("-", " ");
propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);
System.out.println(propertyPageTitle);
Supposing I wanted to ignore the word 'and' if it appears (I'm reading values from a .csv) and NOT change to titlecase? 假设我想忽略单词'和',如果它出现(我正在读取.csv中的值)而不是更改为标题? how would that be possible.
怎么会这样呢?
WordUtils.capitalizeFully不会更改原始String,而是返回大写字符串。
propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);
This happens because capitalizeFully(String)
of WordUtils
returns a String
which has the expected answer. 发生这种情况是因为
WordUtils
capitalizeFully(String)
返回一个具有预期答案的String
。 So try: 所以尝试:
propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);
And then it will work. 然后它会工作。
String firstStr = "i am fine";
String capitalizedStr = WordUtils.capitalizeFully(firstStr);
System.out.println(capitalizedStr);
The return should be taken to get the output of a method. 应该返回以获取方法的输出。 It is common for all methods in Java String
Java String中的所有方法都很常见
String toBeCapped = "1 the high street and 2 low street";
String[] tokens = toBeCapped.split("\\s");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
if (!tokens[i].equalsIgnoreCase("and")) {
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
builder.append(" ");
builder.append(capLetter);
builder.append(tokens[i].substring(1, tokens[i].length()));
} else {
builder.append(" and");
}
}
toBeCapped = builder.toString().trim();
System.out.println(toBeCapped);
output: 输出:
1 The High Street and 2 Low Street
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.