Compare two strings

I have the following code:

    int t = s.length()-1;
    int g = 0;

    for (int i=0; i < s.length(); i++){

        if (s.charAt(i) != h.charAt(t--));
            g++;

    }

    if (g==0)
        return true;

    else 
        return false;

Basically, what this code should do is check if string h is inverse equal to string s, or vice versa. For some reason, “falsehood” always returns, although the obvious answer is correct.

Can anyone tell me what happened to my code?

Thank!

+3
source share
4 answers

I would say that extra ;is the culprit.

Instead

if (s.charAt(i) != h.charAt(t--));

using

if (s.charAt(i) != h.charAt(t--))

You should always take a "safe" route. That is, use curly braces after if-else statements (and almost everywhere you can use them), so errors like this will not happen in the first place. The correct way to write:

if (s.charAt(i) != h.charAt(t--)) {
   g++;
}

, , , , s h .

+8

extra ; if (s.charAt(i) != h.charAt(t--));

if (s.charAt(i) != h.charAt(t--))
{
  g++;
  break; // if not match, not need to continue with loop
}
+3

If this is not a training exercise, I would advise you not to write the loops themselves and use some kind of library code. You can do:

String s = "abcd";
String h = "dcba";

System.out.println( h.equals( new StringBuffer(s).reverse().toString() ) );

or StringUtils # reverse .


Under the hood, these loops go through the string the same way you do. The code is in AbstractStringBuilder if you want to take a look.

+1
source

use break;to exit loop if it doesn't have the same char

bool g = true;
for(.....)
{
   if (s.charAt(i) != h.charAt(t--))
   {
      g = false;
      break;
   }
}
return g;

It increases productivity.

0
source

Source: https://habr.com/ru/post/1796459/


All Articles