KaiquanMah commited on
Commit
db7ae7d
·
verified ·
1 Parent(s): 78bbc3c

Create 13a. string methods

Browse files
Week 2: Methods, strings and lists/13a. string methods ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // indexOf - starting idx of the 1st matching character of the substring
2
+ String s = "An example";
3
+ s.indexOf("xample") == 4;
4
+
5
+
6
+ // contains
7
+ Examples of method usage:
8
+ String start = "I am really starting to get into Java.";
9
+
10
+ System.out.println(start.contains("really"));
11
+ System.out.println(start.contains("java")); // written in lowercase
12
+
13
+ System.out.println(start.indexOf("am"));
14
+ System.out.println(start.indexOf("java"));
15
+
16
+
17
+ Program outputs:
18
+ true
19
+ false
20
+ 2
21
+ -1
22
+
23
+
24
+
25
+
26
+ // replace
27
+ String start = "I am really starting to get into Java.";
28
+ String fixed = start.replace("Java", "C#");
29
+ System.out.println(fixed);
30
+
31
+ Program outputs:
32
+ I am really starting to get into C#.
33
+
34
+
35
+
36
+ // NO IN-PLACE REPLACEMENT OF SUBSTRING
37
+ A typical mistake when using the replace method is to forget that the method DOES NOT MODIFY the original string.
38
+ For example, the following code will not return an error
39
+
40
+ String nephews = "Huey, Dewey and Rouie";
41
+ nephews.replace("Rouie", "Louie");
42
+ System.out.println(nephews);
43
+
44
+ Program outputs:
45
+ Huey, Dewey and Rouie
46
+
47
+
48
+ VS
49
+
50
+ // ASSIGNING BACK TO THE SAME VARIABLE
51
+ String nephews = "Huey, Dewey and Rouie";
52
+ nephews = nephews.replace("Rouie", "Louie");
53
+ System.out.println(nephews);
54
+
55
+
56
+ Program outputs:
57
+
58
+ Huey, Dewey and Louie
59
+
60
+
61
+