Java 在没有替换方法的情况下从字符串中删除所有出现的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20236599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:28:47  来源:igfitidea点击:

Removing all occurrences of a character from string without replace method

java

提问by crazymouse

I need to write a method called remove()that takes two arguments, a Stringand a char, and returns a new String that removes all occurrences of the char from the input String. I have to do this without using the replace()method. So far I have:

我需要编写一个名为的方法remove(),它接受两个参数 aString和 a char,并返回一个新字符串,该字符串从输入字符串中删除所有出现的字符。我必须在不使用该replace()方法的情况下执行此操作。到目前为止,我有:

public class Remover
{
   public static void main (String[] args)
    {
        String sampleString = "this is some text";
        char sampleChar = 's';
        System.out.print(remove(sampleString, sampleChar));
    }
    public static String remove(String a, char b)
    {
      String newString = "";
        newString = a.substring(0, a.indexOf(b))+""+a.substring(a.indexOf(b)+1);

        return newString;
    }
}

The main method is just there for testing purposes and the sample string and char are just examples; I need this method to work for any string and char. But either way, I'm sure what I have is wrong and I'm completely lost on how to proceed. For this case, I'm trying to get my code to return

主要方法仅用于测试目的,示例字符串和字符只是示例;我需要此方法适用于任何字符串和字符。但无论哪种方式,我都确定我的想法是错误的,而且我完全不知道如何继续。对于这种情况,我试图让我的代码返回

"thi i ome text"

回答by Sage

  1. Get chararray from the string using string.toCharArray()method.
  2. Traverse the chararray. Append the charto a String if it is not equal to your target char
  3. Use StringBuilderclass for appending: building the string.
  1. char使用string.toCharArray()方法从字符串中获取数组。
  2. 遍历char数组。char如果它不等于您的目标,则将附加到字符串char
  3. 使用StringBuilder类进行追加:构建字符串。

回答by Paul Samsotha

You can iterate through the String using charAt()

您可以使用遍历字符串 charAt()

String s = "this is some text";

public static String remove(String a, char b) {

    String word = "";

    for (int i = 0; i < a.length(); i++){
        if (s.charAt(i) != b){
            word += a.charAt(i);
        }
    }

    return word;

}

An alternative to String concatenating is to use StringBuilderinside the loop

字符串连接的替代方法是StringBuilder在循环内使用

StringBuilder sb = new StringBuilder();

for (int i = 0; i < a.length(); i++){
    if (s.charAt(i) != b){
        sb.append(s.charAt(i));
    }
}

return sb.toString();

Another way to approach this is to convert the String to a char array and traverse the array

解决此问题的另一种方法是将 String 转换为 char 数组并遍历该数组

 StringBuilder sb = new StringBuilder;

 for (char c : s.toCharArray()){
     if (c != b) {
         sb.append(c);
     }   
 }

 return word;

回答by Maroun

I'll not suggest an alternative solution, I'll tell you how to fix the problem in your currentcode.

我不会建议替代解决方案,我会告诉您如何解决当前代码中的问题。

Your program works only for the first occurrence of s. You should do the following:

您的程序仅适用于第一次出现的s. 您应该执行以下操作:

  1. Split the string according to " ".
  2. Pass each word in the array to removemethod.
  3. Print the result on the same line with " ".
  1. 根据 分割字符串" "
  2. 将数组中的每个单词传递给remove方法。
  3. 将结果打印在同一行" "

Should have something like that:

应该有类似的东西:

String sampleString = "this is some text";
String[] arr = sampleString.split(" ");
char sampleChar = 's';
for(String str : arr) {
    System.out.print(remove(str, sampleChar) + " ");
}

Note that in removemethod, you should check if the String contains s, if not, return it as it is:

请注意,在remove方法中,您应该检查 String 是否包含s,如果没有,则按原样返回:

public static String remove(String a, char b) {
   if(!a.contains(b)) {
      return a;
   }
   String newString = "";
   newString = a.substring(0, a.indexOf(b))+""+a.substring(a.indexOf(b)+1);
   return newString;
}

This should work.

这应该有效。

回答by Subin Sebastian

You can use recursion like below. But still use StringBuilder,that s the better way. This is just to make your code work

您可以使用如下递归。但是还是使用StringBuilder,那是更好的方法。这只是为了让您的代码工作

public static String remove(String a, char b)
{
   String newString = "";
   newString = a.substring(0, a.indexOf(b))+""+a.substring(a.indexOf(b)+1);
   if(newString.indexOf(b)!=-1) {
     newString= remove(newString,b);
   }
   return newString;
}

回答by MouseLearnJava

You can convert the source string to char array using a.toCharArray()),

您可以使用a.toCharArray()),将源字符串转换为字符数组,

then write a for-loop to compare the char element in char array one-by-one with expected removed char.

然后编写一个 for 循环来将 char 数组中的 char 元素与预期删除的 char 一一比较。

If it is not equal, then append it to StringBuilder object.

如果不相等,则将其附加到 StringBuilder 对象。

have a try with this;

试试这个;

 public static String remove(String a, char b) {
    /*String newString = "";
    newString = a.substring(0, a.indexOf(b)) + ""
            + a.substring(a.indexOf(b) + 1);

    return newString;*/

    StringBuilder sb = new StringBuilder();

    for(char c: a.toCharArray())
    {
        if(c!= b)
        {
            sb.append(c);
        }
    }
    return sb.toString();
}

回答by Phoenix

public class charReplace{
    public static void main(String args[]){
    String sampleString = "This is some text";
    char sampleChar = 's';
    System.out.println(char_remove(sampleString, sampleChar));
}

public static String char_remove(String a, char b){
    String newString = " ";
    int len = a.length();
    for(int i =0; i<len ;i++)
     {
       char c = a.charAt(i);
       if(c == b)
          newString = newString + " ";
       else
          newString = newString + c ;  
     }
    return newString;
  }
}

回答by Illakia 9688

 public static String remove(String a, char b)
    {
       StringBuilder sbul =new StringBuilder();
       int i;
        for(i=0;i<a.length();i++){
              char c = a.charAt(i);
               if(c==b)
                  continue;
                sbul.append(c);
             }
        return sbul.toString();
}