1

I want to match two string in the same list. I want to get words from a string and insert into list. I want to remove white space and separate by commas. Then I want to check two string in that list whether match or not.

Here is my code:

main() {
  List<String> list = new List();
  String str = "dog , dog , cat, tiger, lion, cat";
  String strn = str.replaceAll(" " , "");
  list = strn.split(",");

  print(list.length);
  print(list);

  for (int i=0;i<list.length;i++){
    if (list[i] == list[i+1]) {
      print("same");
    } else{
      print("not same");
    }
    i++;
  }
}

here string only check upto length 4. and white space not removed!

3
  • 1
    What is your question? I can see that you increment i twice (i++ in the for header and in its body) and that you count one too far in the loop (if i is list.length - 1 then list[i+1] will throw, you just happen to dodge this by incrementing i twice so it never hits the value 5). Commented Oct 18, 2018 at 11:30
  • My question why it doesn't hit index 4 and 5? and why it doesn't remove white space? Commented Oct 18, 2018 at 11:40
  • The double increment of i answers the first question (it actually doesn't hit indices 1, 3 and 5). Also, it does remove white-space. Instead of print(list);, try using print(list.join(","));. The List.toString method adds comma+space between elements. Commented Oct 18, 2018 at 13:47

1 Answer 1

1

I also noticed that in the for loop you are incrementing i twice, the second being close to the bottom. This causes i to skip some of the indexes, so loop looks at index 0, then 2, then 4, then it stops.

I have refactored your solution slightly. I removed the second i++ and changed i < list.length to i < list.length - 1 to skip the last item as list[i + 1] will throw an out of range exception:

main() {
  List<String> list = new List();
  String str = "dog , dog , cat, tiger, lion, cat";
  String strn = str.replaceAll(" ", "");
  list = strn.split(",");

  print(list.length);
  print(list.join('|'));

  for(int i=0; i < list.length - 1; i++){
    if(list[i] == list[i+1]){
      print("same");
    }
    else{
      print("not same");
    }
  }
}

The result of the loop is so:

same
not same
not same
not same
not same

You can test this out on DartPad

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.