-1

I have a problem where a string for eg. "dancing" is given and two indexes n=3,m=10 is given. We have to check whether the char at both index is same.

Which is true in this case when the string is repeated as [dancingdancing]. The 3rd and 10th character is n. How do I solve this in java?

Naman
  • 27,789
  • 26
  • 218
  • 353
HarshRaj
  • 11
  • 1
  • 1
    Use the modulo operator `%` – Oleg Mar 28 '20 at 07:57
  • [Concatenate or Merge strings](https://stackoverflow.com/questions/25608315/concatenate-or-merge-strings-java) [How can i access a char in string in at specific number?](https://stackoverflow.com/questions/50297288/how-can-i-access-a-char-in-string-in-at-specific-number) [How do you compare characters in java?](https://stackoverflow.com/questions/16474475/how-do-you-compare-characters-in-java) – Max Vollmer Mar 28 '20 at 08:03

1 Answers1

1

You can check the characters at two indexes are same by updating the value of the second index provided such as :

String str = "dancing";
int first = 3;
int second = 10;

first = first % str.length();
second = second % str.length();
Assert.assertTrue(str.charAt(first) == str.charAt(second))
Naman
  • 27,789
  • 26
  • 218
  • 353
  • Ok thanks. But why do we use Assert? – HarshRaj Mar 28 '20 at 12:37
  • @HarshRaj Just to confirm that for the given input, your expected result is achieved. It's just a way to write it, you could, for example, validate that using `System.out.println(str.charAt(first) == str.charAt(second))` as well. – Naman Mar 28 '20 at 12:49
  • Naman This approach is failing for some input such as "mail" for index 5 and 14. – HarshRaj Mar 28 '20 at 12:58
  • @HarshRaj If the first index as well could be greater than the length as well, just repeat the same process. Updated in the answer. – Naman Mar 28 '20 at 13:15