forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.java
More file actions
99 lines (79 loc) · 2.62 KB
/
Copy pathStrings.java
File metadata and controls
99 lines (79 loc) · 2.62 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
/**
* Demonstates uses of Strings.
*/
public class Strings {
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();
// String iteration
for (int i = 0; i < fruit.length(); i++) {
char letter = fruit.charAt(i);
System.out.println(letter);
}
int length = fruit.length();
char last = fruit.charAt(length - 1); // correct
System.out.println(reverse(fruit));
// The indexOf method
int index = fruit.indexOf('a');
int index2 = fruit.indexOf('a', 2);
// 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));
// 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 + ", lexicographically");
} else if (diff > 0) {
System.out.println(name2 + " comes before " + name1 + ", lexicographically");
}
}
/**
* 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;
}
public static boolean isPalindrome(String s) {
return s.equals(reverse(s));
}
public static String copy(String s) {
char[] c = s.toCharArray();
// Concatenate the characters into this variable:
String newString = "";
// Form a new string in a loop
for (int i = 0; i < c.length; i++) {
newString = newString + c[i];
}
// After the loop, return the new string
return newString;
}
}