lowercase first letter and use “underscore” instead of “space” in Java

huangapple go评论114阅读模式
英文:

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 &lt; str.length(); i++) {
        char ch = str.charAt(i);
        buf.append(ch == &#39; &#39; ? &#39;_&#39; : Character.toLowerCase(ch));
    }
    
    return buf.toString();
}

P.S. Sure it could be more another solutions e.g. like str.replace(&quot; &quot;, &quot;_&quot;).toLowerCase(). My solution uses StringBuilder which is correct way buil String and does not use Regexp. Time complexity is O(n).

huangapple
  • 本文由 发表于 2020年9月17日 15:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63933612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定