Skip to content

Instantly share code, notes, and snippets.

@mvexel
Last active November 18, 2017 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvexel/cdd6144a4bfd361adf161beabc5fefbc to your computer and use it in GitHub Desktop.
Save mvexel/cdd6144a4bfd361adf161beabc5fefbc to your computer and use it in GitHub Desktop.
StringSearch
public class StringSearch {
public static void main(String[] args) {
// Initialize a new String
String myString = "Thanksgiving Day";
System.out.println("Our string is: " + myString);
// Now, get the 3rd letter in this string.
// Remember that indexes are zero based,
// so the third character has index 2, not 3.
char myThirdLetter = myString.charAt(2);
System.out.println("The third letter is: " + myThirdLetter);
// Now we want to know the first location where
// the letter 'g' occurs in our string.
int myFirstG = myString.indexOf('g');
System.out.println("The first time the letter g occurs is at location: " + myFirstG);
// If the character is not found, indexOf will
// return -1
int myFirstQ = myString.indexOf('q');
System.out.println("The first time the letter q occurs is at location: " + myFirstQ);
// You can alse start your search at a specific
// location in the string. Let's start at location 7.
int mySecondG = myString.indexOf('g', 7);
System.out.println("The first time the letter g occurs after location 6 is at location: " + mySecondG);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment