1

Say my string is as follows

String str = "What is up tod?";

I want to use an accessor method to print out the position of the first occurrence of the letter "t". What is an efficient use of code to use? I also want to ensure that it doesn't try to tell me the occurrence of the second "t". Please keep in mind I am searching for how to do this in Java.

Any help or link to similar question is greatly appreciated.

1 Answers1

1

Unless I'm missing something, use String.indexOf(int) like

String str = "What is up tod?";
System.out.println(str.indexOf('t'));

Which outputs the first match

3

Alternatively, iterate the characters of the String from left to right checking for 't'; if you find it, print the index and terminate the loop. Like,

String str = "What is up tod?";
for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i) == 't') {
        System.out.println(i);
        break;
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • That works for what I am attempting to use this for thank you, I kept getting redirected to useful links however a bit more complicated than I needed. – Cahill Howell May 21 '20 at 02:47