英文:
Lowercase first letter and use "_" instead of " " in Java
问题
我有一个Java程序,我想将字符串中单词的每个字符都转换为小写,并将空格“ ”替换为“_”。以下是一些示例:
- "Tall Building" --> "tall_building"
- "Red Shoes" --> "red_shoes"
- "Water" --> "water"
如果可能的话,我不想使用任何库。你介意告诉我如何做吗?我会很感激每一条建议。
英文:
I have a Java programm and I would like to make every character of a word in a String a lowercase character and replace an empty space " " by a "_". So here are some expample:
- "Tall Building" --> "tall_building"
- "Red Shoes" --> "red_shoes"
- "Water" --> "water"
I do not want to use any libarary if that is possible. Would you mind telling me how I can do that? I'd appreciate every comment.
答案1
得分: 1
public static String modifyString(String str) {
if (str == null)
return null;
if (str.isEmpty())
return str;
StringBuilder buf = new StringBuilder(str.length());
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
buf.append(ch == ' ' ? '_' : Character.toLowerCase(ch));
}
return buf.toString();
}
P.S. 当然还有其他解决方案,比如 str.replace(" ", "_").toLowerCase()
。我的解决方案使用了 StringBuilder
,这是构建 String
的正确方式,而且没有使用正则表达式。时间复杂度为 O(n)
。
英文:
public static String modifyString(String str) {
if (str == null)
return null;
if (str.isEmpty())
return str;
StringBuilder buf = new StringBuilder(str.length());
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
buf.append(ch == ' ' ? '_' : Character.toLowerCase(ch));
}
return buf.toString();
}
P.S. Sure it could be more another solutions e.g. like str.replace(" ", "_").toLowerCase()
. My solution uses StringBuilder
which is correct way buil String
and does not use Regexp
. Time complexity is O(n)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论