简体   繁体   中英

Given two strings, str1 and str2 as input, remove all chars from str1 that appear in str2

Given two strings, str1 and str2 as input, remove all chars from str1 that appear in str2.

MYApproach

In my function I took 2 Strings.In for loop I am checking each character position whether that character in string1 matches in string2.If it does not match I increment a count.If it matches I do not increment.I also checked whether count is qual to my length of second string.If it does,I then added String1 character to a new String

Below is my Updated Code for today:

 public String remove(String str1, String str2)
{
     String strnew="";
     int count=0;
     int p=0;
     //int j=0;
     int l1=str1.length();
     int l2=str2.length();
     for(int j=0;j<l1;)
     {
        char ch1=str1.charAt(p);
        char ch2=str2.charAt(j);
        if(ch1!=ch2)

        {   
             count++;

             j++;

           if(count==l1)
           {
             strnew=strnew+ch1;
             p++;
             j=0;
             count=0;
            }

        } 

        else
        {
            p++;
            count=0;
            j=0;
        }

     }
    return strnew;
    //write your code here


}       

}

I am getting the following error:

Output       TestcaseParameters Testcase Actual Answer  Expected

No output   'Hello''World'                null             He

Can anyone tell me why I am getting this error?

Thank you in advance.

There are at least three errors in your logic:

(1) It looks like you're going through str1 , to see if any character matches the current character in str2 . You keep a count of the characters that don't match. Then, when the count reaches the limit, you decide it's not a match and you add it to the result string.

However, what's the limit? Since you're going through str1 (using j ), the limit should be the number of characters in str1 . But you're checking count==l2 , and l2 is the number of characters in str2 --the wrong one.

As it happens, the test case has the same length for both, so that's not the reason this test case is failing. But it will cause other test cases to fail.

(2) The more serious problem is where you're doing the check. Say you get to the last character of str1 . You find that the character doesn't match. So you increment count , which will now equal the length of str1 , after you fix the first problem. So the program is supposed to check that count equals the length, and behave accordingly.

But it doesn't get to that check , because you stuck it in an else . When ch1!=ch2 is true, the program executes the body of the if and then skips over the else blocks. The result will be that the next time it goes through the loop again, j is too large, and you'll get an out-of-bounds exception, which apparently this tester is unable to handle gracefully ( [object Object] ? Really now.....)

(3) One more problem is, your code will end in only one loop.Your loop condition is based on 'l1' and you are not resetting it when the loop ends. So, if no match is found for a letter, the loop will end then and there. Since, "Hello" does not contain any 'W', the loop will end when j and 'l1' becomes equal at the fifth iteration after checking for 'W' in 'str1'.

Would you consider using more intuitive way, such as two layers of for-loop? Please try the following code (I have tested it):

public String remove(String str1, String str2) {
    String strnew = "";
    int l1 = str1.length();
    int l2 = str2.length();
    for (int j = 0; j < l1; j++) {
        char ch1 = str1.charAt(j);
        boolean isMatched = false;
        for (int p = 0; p < l2; p++) {
            char ch2 = str2.charAt(p);
            if (ch1 == ch2) {
                isMatched = true;
                break;
            }
        }
        if(!isMatched) {
            strnew += ch1;
        }
    }
    return strnew;
}

Well if your parameters are "Hello" and "World"

the resulting path will be as followed for your original program:

String strnew = "";
l1=ch1.length()// l1 = 5
if(ch1!=ch2)   // 'H' != 'W'
   continue;
for(;j<l1;j++) // j = 1
if(ch1!=ch2)   // 'e' != 'W'
   continue;
for(;j<l1;j++) // j = 2
if(ch1!=ch2)   // 'l' != 'W'
   continue;
for(;j<l1;j++) // j = 3
if(ch1!=ch2)   // 'l' != 'W'
   continue;
for(;j<l1;j++) // j = 4
if(ch1!=ch2)   // 'o' != 'W'
   continue;
for(;j<l1;j++) // j = 5, (j < l1) is now false
break;         // (j < l1) being false causes the loop to end
return strnew; // still ""

Also make sure the question asks you for characters and not letters. If it asks for letters then you should either lowercase or uppercase all the letters in both strings for comparison.

Finally, the problem with your code printing object is not shown within your code here. if you directly printed the result would just not print anything since it is an empty string.

function processStrings(str1, str2) {
    let str1Out="";
    let str2Out="";
    let x1 = str1.length;
    let x2 = str2.length;
    let output=[];

    for(let i=0; i < x1; i++){
        let occr = 0;
        for(let j=0; j < x2; j++){
            if(str1[i] != str2[j]){
                occr = occr+1;
                if(j == x2-1 && occr > 0){
                    str1Out = str1Out.concat(str1[i]);
                }
            }
            else if(str1[i] == str2[j]){
                break;
            }
        }
    }
     console.log(str1Out, 'str1Out');
    for(let i=0; i < x2; i++){
        let occr = 0;
        for(let j=0; j < x1; j++){
            if(str2[i] != str1[j]){
                occr = occr+1;
                if(j == x1-1 && occr > 0){
                    str2Out = str2Out.concat(str2[i]);
                }
            }
            else if(str2[i] == str1[j]){
                break;
            }
        }
    }
    console.log(str2Out, 'str2Out');

}

I think you are not getting any output, because of your first if clause.

if(ch1!=ch2)

The problem with this clause is, that it does NOT compare the values of the characters, but rather checks if they have the same address in memory. To solve your problem you should compare the characters like this:

if(!ch1.equals(ch2))

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