File size: 1,225 Bytes
db7ae7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 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