Remove the input string from the original myString

Viewed 115

I am trying to remove the input string from the public string myString

myString = "Hello"

removeS("el") will return "Hlo"

Heres my code below and the problem in it is incompatible types: java.lang.String cannot be converted to int in my String result. I would like it if you used substring() and indexOf() to solve my issue and not use any other power tools than those. How would I go about fixing this.

public class StringI
{
    public String myString;

public String removeS(String s){

    myString = "Hello";
    
    
    String result = s.substring(myString);

    return result;
    }

public static void main(String args[]){

StringI n = new StringI();

n.removeS("el");


}




}


3 Answers

We need to get the first half and the last half, then piece them together like so:

String result = myString.substring(0, myString.indexOf(s))+myString.substring(myString.indexOf(s)+s.length());

Since .indexOf() returns the position of s, we can use substring to start from the start of the String to that position, then use another substring to get the final part.

The following program:

import java.util.Scanner; 
 
 public class Main {
     public static String removeS(String s){
         String myString = "Hello";
         String result = myString.substring(0, myString.indexOf(s))+myString.substring(myString.indexOf(s)+s.length(), myString.length());
         return result;
     }
 public static void main(String[] args) {
    System.out.println(removeS("el"));
 }
}

Produces:

Hlo

Using Substring: You can make this into two part:

public class StringI
{
    public String myString;

    public String removeS(String s){
        myString = "Hello";
        
        // Before the `s`
        String part1 = myString.substring(0, myString.indexOf(s));
        // After the `s`
        String part2 = myString.substring(myString.indexOf(s) + s.length());

        return part1 + part2;
    }

    public static void main(String args[]){
        StringI n = new StringI();
        String result = n.removeS("el");
        
        System.out.println(result);
    }
}

The easiest way to do is-

public static void main(String[] args) {
    String myString = "Hello";
    String removeString="el";
    System.out.println(myString.replace(removeString,""));
}
Related