替换String中字符的所有实例

时间:2015-11-15 00:13:20

标签: java

我正在尝试创建一个方法,用一个新字符替换单词中某个字符的所有实例。这就是我到目前为止所做的:

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;
}

}

我希望它返回t-t,但它只打印最后一个t。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

Java已经在String中有一个内置方法。您可以使用replace()方法将字符串中给定字符的所有匹配项替换为另一个字符

<link href="~/Content/jquery-ui-timepicker-addon.css" rel="stylesheet" />
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery-ui.structure.css" rel="stylesheet" />
<link href="~/Content/jquery-ui.theme.css" rel="stylesheet" />


<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-ui-timepicker-addon.js"></script>
<script src="~/Scripts/jquery-ui-sliderAccess.js"></script>


<input type="text" name="basic_example_1" id="basic_example_1" value="" class="hasDatepicker">

<script type="text/javascript">
    $('#basic_example_1').datetimepicker();
</script>

答案 1 :(得分:0)

我怀疑你正在寻找像

这样的东西
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);
}

答案 2 :(得分:0)

在您的代码中,每次找到该字符时都会覆盖String。您应该每次都扩展字符串,而不是覆盖。

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();
  }

}