-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample105.java
More file actions
48 lines (43 loc) · 1.27 KB
/
Example105.java
File metadata and controls
48 lines (43 loc) · 1.27 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
// Example 105 from page 79
//
import java.util.Random;
class Example105 {
public static void main(String[] args) {
if (args.length != 1)
System.out.println("Usage: java Example105 <length>\n");
else {
System.out.println("Timing character replacement in a string:");
Random rnd = new Random();
int length = Integer.parseInt(args[0]);
char[] cbuf = new char[length];
for (int i=0; i<length; i++)
cbuf[i] = (char)(65 + rnd.nextInt(26));
String s = new String(cbuf);
for (int i=0; i<10; i++) {
Timer t = new Timer();
String res = replaceCharString(s, 'A', "HA");
System.out.print(t.check() + " ");
}
System.out.println();
}
}
static String replaceCharString(String s, char c1, String s2) {
StringBuilder res = new StringBuilder();
for (int i=0; i<s.length(); i++)
if (s.charAt(i) == c1)
res.append(s2);
else
res.append(s.charAt(i));
return res.toString();
}
// Simple timer, measuring wall-clock (elapsed) time in seconds
private final static class Timer {
private long start;
public Timer() {
start = System.nanoTime();
}
public double check() {
return (System.nanoTime() - start) / 1e9;
}
}
}