简体   繁体   English

替换String中字符的所有实例

[英]Replace all instances of a character in a String

I'm trying to create a method that replace all instances of a certain character in a word with a new character. 我正在尝试创建一个方法,用一个新字符替换单词中某个特定字符的所有实例。 This is what I have so far: 这是我到目前为止:

public class practice {
public static void main(String[] args) {

    String test3 = updatePartialword("----", "test", 't');
    System.out.println(test3); }


public static String updatePartialword(String partial, String secret, char c) {
    String newPartial = "";
    int len = secret.length();
    for (int i=0; i<=secret.length()-1; i++){
        char x = secret.charAt(i);
        if (c==x) {
            String first = partial.substring(0,i);
            String second = partial.substring(i+1,len);
            newPartial = first+x+second;
        }


    }
        return newPartial;
}

}

I want it to return t--t, but it will only print the last t. 我希望它返回t - t,但它只打印最后一个t。 Any help would be greatly appreciated! 任何帮助将不胜感激!

Java already has a built in method in String for this. Java已经在String中有一个内置方法。 You can use the the replace() method to replace all occurrences of the given character in the String with the another character 您可以使用replace()方法将String中给定字符的所有匹配项替换为另一个字符

    String str = "Hello";
    str.replace('l', '-'); //Returns He--o
    str.replace('H', '-'); //Returns -ello

I suspect you are looking for something like 我怀疑你正在寻找类似的东西

public static void main(String[] args) {
    String test3 = updatePartialword("----", "test", 't');
    System.out.println(test3);
}

public static String updatePartialword(String partial, String secret, char c) {
    char[] tmp = partial.toCharArray();

    for (int i = 0; i < secret.length(); i++) {
        char x = secret.charAt(i);
        if (c == x) {
            tmp[i] = c;
        }

    }
    return new String(tmp);
}

In your code you overwrite the String each time you found the character. 在您的代码中,每次找到该字符时都会覆盖String。 Instead of overwriting, you should expand the string each time. 您应该每次都扩展字符串,而不是覆盖。

public class practice {
  public static void main(String[] args) {
    String test3 = updatePartialword("----", "test", 't');
    System.out.println(test3); 
}

public static String updatePartialword(String partial, String secret, char c) {
    StringBuilder sb = new Stringbuilder();
    sb.append(""); // to prevent the Stringbuilder from calculating with the chars
    for (int i = 0; i < partial.lenght; i++)
      if (secret.charAt(i) == c)
        sb.append(c);
      else
        sb.append('-');
    return sb.toString();
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM