【发布时间】:2015-05-02 06:51:17
【问题描述】:
我有一个程序可以将 String 中的数字 0-9 转换为它们的文本等价物(例如:“0”变成“零”)。但是,当数字在句子的开头时,我需要将其大写。
示例
4 dogs were chasing 3 cats.
The 8 eggs were separated into 3 groups.
变成:
four dogs were chasing three cats.
The eight eggs were separated into three groups.
代码
public String ConvertSentance(String s){
sb = new StringBuilder();
h.put("0","zero");
h.put("1","one");
h.put("2", "two");
h.put("3", "three");
h.put("4", "four");
h.put("5", "five");
h.put("6", "six");
h.put("7", "seven");
h.put("8", "eight");
h.put("9", "nine");
String[] split = s.split(" ");
for (String newS : split) {
if (h.containsKey(newS)) {
sb.append(h.get(newS));
sb.append(' ');
}
else {
sb.append(newS);
sb.append(' ');
}
}
convertedSent = sb.toString();
return sb.toString();
}
我怎样才能让这个大写开头的字符,以便输出变成这个?
Four dogs were chasing three cats.
仅当它们的编号位于句子的开头时,我才无法使其正常工作。我尝试了for-loops 的不同变体,但没有成功。
【问题讨论】:
-
return convertedSent.substring(0, 1).toUpperCase() + convertedSent.substring(1);将字符串的第一个字符大写
标签: java arrays string split hashmap