简体   繁体   中英

how to remove a string from a code using methods, arrays and loops?

I made a code that removes symbols and characters from a "string text" using "method" and "arrays" and "loops", and everything was built in successfully.

But, when I tried testing it on an actual String text, it wasn't running. Someone clarify what I did wrong. here is the code:

public static String remove(String text, char symbol){
    String a= " ";
    for(int i=1; i<text.length();i++){
        char letter=text.charAt(i);
        if(letter !=symbol){
            a+=letter;
        }
    }
    return a;
}

There are a few problems in your code:

  1. a = " " doesn't seem to be correct, unless you want to have a space at the beginning of the result-string.
  2. The iteration in your for-loop starts at i = 1 . That's not correct either, because that way you will not work on the first letter in the string.

A corrected - and working - solution looks like this:

public class RemoveLetter {
    public static void main(String[] args) {
        System.out.println(remove("Hello World", 'o')); 
    }
    public static String remove(String text, char symbol){
        String a= "";
        for(int i = 0; i < text.length(); i++){
            char letter = text.charAt(i);
            if(letter != symbol) {
                a += letter;
            }
        }
        return a;
    }
}

This example will give the output Hell Wrld , which certainly is correct.

Edit To remove more than one letter, you will have to call the method multiple times:

public class RemoveLetter {
    public static void main(String[] args) {
        String string = "Hello World";
        String result = remove(string, 'o');
        result = remove(result, 'H');
        System.out.println(result);  
    }
    public static String remove(String text, char symbol){
        String a= "";
        for(int i = 0; i < text.length(); i++){
            char letter = text.charAt(i);
            if(letter != symbol) {
                a += letter;
            }
        }
        return a;
    }
}

This will give you the output ell Wrld .

i is not 1, it should be 0. Try this code:

public static String remove(String text, char symbol) {

    StringBuilder a = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
        char letter = text.charAt(i);
        if (letter != symbol) {
            a.append(letter);
        }
    }
    return a.toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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