Spaces:
Running
Running
| // indexOf - starting idx of the 1st matching character of the substring | |
| String s = "An example"; | |
| s.indexOf("xample") == 4; | |
| // contains | |
| Examples of method usage: | |
| String start = "I am really starting to get into Java."; | |
| System.out.println(start.contains("really")); | |
| System.out.println(start.contains("java")); // written in lowercase | |
| System.out.println(start.indexOf("am")); | |
| System.out.println(start.indexOf("java")); | |
| Program outputs: | |
| true | |
| false | |
| 2 | |
| -1 | |
| // replace | |
| String start = "I am really starting to get into Java."; | |
| String fixed = start.replace("Java", "C#"); | |
| System.out.println(fixed); | |
| Program outputs: | |
| I am really starting to get into C | |
| // NO IN-PLACE REPLACEMENT OF SUBSTRING | |
| A typical mistake when using the replace method is to forget that the method DOES NOT MODIFY the original string. | |
| For example, the following code will not return an error | |
| String nephews = "Huey, Dewey and Rouie"; | |
| nephews.replace("Rouie", "Louie"); | |
| System.out.println(nephews); | |
| Program outputs: | |
| Huey, Dewey and Rouie | |
| VS | |
| // ASSIGNING BACK TO THE SAME VARIABLE | |
| String nephews = "Huey, Dewey and Rouie"; | |
| nephews = nephews.replace("Rouie", "Louie"); | |
| System.out.println(nephews); | |
| Program outputs: | |
| Huey, Dewey and Louie | |