-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringPractice.java
More file actions
104 lines (82 loc) · 2.04 KB
/
Copy pathStringPractice.java
File metadata and controls
104 lines (82 loc) · 2.04 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
package introduction;
import java.util.Scanner;
public class StringPractice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Part a
System.out.println("type a word");
String test = in.nextLine();
String newS = expand(test);
System.out.println(newS);
// Part b
System.out.println("type a word");
test = in.nextLine();
System.out.println(reverse(test));
// Part c
System.out.println("type a word");
test = in.nextLine();
System.out.println(compact(test));
// Part d
System.out.println("type a word");
test = in.nextLine();
System.out.println("what character do you want to look for");
char lookFor = in.nextLine().charAt(0);
in.close();
System.out.println("That character appears " + count(test, lookFor) + " times");
}
// Place a hyphen between each letter example: "Buffy" returns "B-u-f-f-y"
private static String expand(String test)
{
String result = "";
result += test.charAt(0);
for (int i = 1; i < test.length(); i++)
{
result += "-" + test.charAt(i);
}
return result;
}
// Reverse the string "Buffy" returns "yffuB"
private static String reverse(String test)
{
String result = "";
for (int j = (test.length() - 1); j >= 0 ; j--)
{
result += test.charAt(j);
}
return result;
}
// Remove spaces "Buffy the wonder dog" returns "Buffythewonderdog"
private static String compact(String test)
{
String result = "";
for (int k = 0; k < test.length(); k++)
{
if (test.charAt(k) != ' ')
{
result += test.charAt(k);
}
else{
//do nothing
}
}
result.trim();
return result;
}
// Count the number of occurrences of a letter in a string
// "Buffy", 'f' --> returns 2
private static int count(String test, char lookFor)
{
int count = 0;
for (int l = 0; l < test.length(); l++)
{
if (test.charAt(l) == lookFor)
{
count++;
}
else {
//do nothing
}
}
return count;
}
}