ETR009
ETR009

Reputation: 15

How to erase certain characters in a string using a for loop?

I'm trying to write a function that takes a String parameter str. It returns a new version where all the "x" characters have been removed. Except an "x" at the very start or end of str should not be removed. I can only use loops for this problem, not StringBuilder or .replace() method.

I'm not sure how to erase a character at a certain string position. So far this is the code I have, any input would be greatly appreciated.

public String stringX(String str)
{
    String result = str;
    int len = str.length() - 1;


    for (int i = 0; i <= len; i++)
    {
        char letter = str.charAt(i);
        if (letter == 'x' && ((i != 0) && (i != len)))
        {

        } 
    }

    return result; 
}

Upvotes: -1

Views: 5089

Answers (3)

Komronbek
Komronbek

Reputation: 1

public String stringX(String str) {
 String a = "";
  if(str.length() > 2){
   String front = str.substring(0,1), 
    back = str.substring(str.length()-1),
     middle = str.substring(1, str.length()-1);
      for(int i = 0; i < middle.length(); i++){
       if(middle.charAt(i) != 'x') a += middle.charAt(i);
      }
      return front + a + back;
  }
 return str;
}

Upvotes: 0

Mohit Tyagi
Mohit Tyagi

Reputation: 2876

I have done some modification in your code :

String result = "";
int len = str.length() - 1;

for (int i = 0; i <= len; i++)
{
    char letter = str.charAt(i);
     if (letter == 'x' && ((i == 0) || (i == len))) {
        result += String.valueOf(letter);
    }        
    else if(letter != 'x'){
        result += String.valueOf(letter);
    }    
}

Upvotes: -1

user6305847
user6305847

Reputation:

You cannot delete a character from a String because the String is immutable (can't be changed). If you want to read a little bit more about this check the documentation out here and read that introductory information.

Basically, this means you need to create a new String that has all the characters you do want.

What you could do is turn your input into a char[] and loop through with your current for loop. When you find a character that isn't an x you can append it to an empty String for output.

public String stringX(String str)
  {
  char[] c = str.toCharArray();
  String result = "";
  int len = str.length() - 1;

  for (int i = 0; i <= len; i++)
  {
    char letter = c[i];
    if (!(letter == 'x' && ((i != 0) && (i != len))))
    {
      result += letter;
    } 
  }

  return result; 
}

This would require changing very little of the code you have, while still offering the desired results.

Upvotes: 0

Related Questions