public String noXYZString s returns a string in which all th

public String noXYZ(String s) returns a string in which all the letters x, y, and z have been removed. You must use a loop.

Example :

input : \"I zwant ya xcat\"

output : \"I want a cat\"

Here\'s my code and got know idea what is the problem

public String noXYZ(String s)
{
int i = 0;
s = s.toLowerCase();
s = s.substring(i, i+1);
do
{
if ( s.contains(\"x\"))
{
s = s.replace(\"x\", \"\");
}
if ( s.contains(\"y\"))
{
s = s.replace(\"y\", \"\");
}
if ( s.contains(\"z\"))
{
s = s.replace(\"z\", \"\");
}
i ++;
}
while (i < s.length());
return s;
}

Solution

The code given by you is doing a wrong logic. Please find below the errors :

Here you have defined s = s.substring(i, i+1); which is nothing but returns one character, and inside while condition you have given while (i < s.length()); that is it will executes only when i is < s.length(), here s length is 1. Thus the loop will execute only once, and it returns only first character.

Instead of this, you can use the following implementation, which is probably easy :

public String noXYZ(String s) returns a string in which all the letters x, y, and z have been removed. You must use a loop. Example : input : \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site