Search code examples
javastringsubstringstring-length

In Java, how can I create a method where I can remove/add letters or numbers to a certain String?


I know how to access a certain string spot using a for loop and doing string.substring(i), but I do not know to remove or add letters/numbers.

String.substring(i).replace("x", "");

public static String replace(String s) {
    for (int i=0; i<s.length(); i++) {
            if (s.substring(i) == ... ) {
                //more code
            }
    }
}

When I run this code, it still prints the original String.


Solution

  • String is immutable in java . You can make StringBuilder object from String and do remove and add opertaion on it. StringBuilder gives you a methods deleteCharAt and setCharAt. You can use them and in the end you can again get your new String back by calling method toString from StringBuilder object.

    StringBuilder sb = new StringBuilder("yourString");
    for(int i=0;i<sb.length();i++){
        if(sb.charAt(i) == '5'){ // want to compare '5' 
          sb.deleteCharAt(i);
        } else {
          sb.setCharAt(i,'6');
        }
    }
    String newString = sb.toString;