D
D
Dmitry072016-08-28 10:25:20
Java
Dmitry07, 2016-08-28 10:25:20

Why is essentially identical code not executed?

Good day.
There is a simple task: take a string and remove from it all substrings of 3 characters. Substrings start with 'y' and end with 'k', and 'yakabc' would, for example, be 'abc'.
The correct solution looks like this:

public String stringСut(String str) {
  String result = "";
  
  for (int i=0; i<str.length(); i++) {
    if (i+2<str.length() && str.charAt(i)=='y' && str.charAt(i+2)=='k') {
      i =  i + 2;
    } else {
      result = result + str.charAt(i);
    }
  }
  
  return result;
}

My solution is very similar, just goes from 'if not equal':
public String stringСut(String str) {
  String result = "";
  
  for (int i=0; i<str.length(); i++) {
    if (i+2<str.length() && str.charAt(i)!='y' && str.charAt(i+2)!='k') {
      result = result + str.charAt(i);
    } else {
      i = i + 2;
    }
  }
  
  return result;
}

This code compiles, but only an empty string is returned. With what it can be connected?
Thanks to.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2016-08-28
@Dmitry07

You incorrectly "inverted" conditions.
It should turn out something like:

(i+2<str.length() && (str.charAt(i)!='y' || str.charAt(i+2)!='k'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question