forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringsThings.java
More file actions
105 lines (78 loc) · 2.59 KB
/
StringsThings.java
File metadata and controls
105 lines (78 loc) · 2.59 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* Demonstates uses of Strings.
*/
public class StringsThings {
public static void main(String[] args) {
// Characters
String fruit = "banana";
char letter0 = fruit.charAt(0);
if (letter0 == 'a') {
System.out.println('?');
}
System.out.print("Roman alphabet: ");
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c);
}
System.out.println();
System.out.print("Greek alphabet: ");
for (int i = 913; i <= 937; i++) {
System.out.print((char) i);
}
System.out.println();
// Strings are immutable
String name = "Alan Turing";
String upperName = name.toUpperCase();
String text = "Computer Science is fun!";
text = text.replace("Computer Science", "CS");
// String traversal
for (int i = 0; i < fruit.length(); i++) {
char letter = fruit.charAt(i);
System.out.println(letter);
}
for (char letter : fruit.toCharArray()) {
System.out.println(letter);
}
int length = fruit.length();
char last = fruit.charAt(length - 1); // correct
System.out.println(reverse(fruit));
// Substrings
System.out.println(fruit.substring(0));
System.out.println(fruit.substring(2));
System.out.println(fruit.substring(6));
System.out.println(fruit.substring(0, 3));
System.out.println(fruit.substring(2, 5));
System.out.println(fruit.substring(6, 6));
// The indexOf method
int index = fruit.indexOf('a');
int index2 = fruit.indexOf('a', 2);
// String comparison
String name1 = "Alan Turing";
String name2 = "Ada Lovelace";
if (name1.equals(name2)) {
System.out.println("The names are the same.");
}
int diff = name1.compareTo(name2);
if (diff == 0) {
System.out.println("The names are the same.");
} else if (diff < 0) {
System.out.println("name1 comes before name2.");
} else if (diff > 0) {
System.out.println("name2 comes before name1.");
}
// Wrapper classes
String str = "12345";
int num = Integer.parseInt(str);
num = 12345;
str = Integer.toString(num);
}
/**
* Reverses a string, returns a new String.
*/
public static String reverse(String s) {
String r = "";
for (int i = s.length() - 1; i >= 0; i--) {
r = r + s.charAt(i);
}
return r;
}
}