Skip to content

Commit f707b15

Browse files
committed
add basic, strcmp
1 parent 066e4ab commit f707b15

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package algorithm.basic;
2+
3+
public class Strcmp {
4+
5+
/**
6+
* If s1 > s2, return 1, if s1 == s2, return 0, else return -1
7+
* @param s1
8+
* @param s2
9+
* @return
10+
*/
11+
public int strcmp(String s1, String s2) {
12+
int pos1 = 0;
13+
int pos2 = 0;
14+
15+
while (pos1 < s1.length() || pos2 < s2.length()) {
16+
if (pos1 == s1.length()) { // s1 reaches the end
17+
return -1;
18+
}
19+
if (pos2 == s2.length()) { // s2 reaches the end
20+
return 1;
21+
}
22+
if (s1.charAt(pos1) < s2.charAt(pos2)) {
23+
return -1;
24+
}
25+
else if (s1.charAt(pos1) > s2.charAt(pos2)) {
26+
return 1;
27+
}
28+
else {
29+
++pos1;
30+
++pos2;
31+
}
32+
}
33+
34+
return 0;
35+
}
36+
37+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package algorithm.basic;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import org.junit.Test;
6+
7+
public class TestStrcmp {
8+
9+
@Test
10+
public void testStrcmp() {
11+
Strcmp cmp = new Strcmp();
12+
String s11 = "abcdedf";
13+
String s12 = "abcdedf";
14+
15+
assertEquals(0, cmp.strcmp(s11, s12));
16+
17+
String s21 = "abcdef";
18+
String s22 = "abcdefg";
19+
20+
assertEquals(-1, cmp.strcmp(s21, s22));
21+
22+
String s31 = "babcdef";
23+
String s32 = "aabcdefg";
24+
25+
assertEquals(1, cmp.strcmp(s31, s32));
26+
}
27+
28+
}

0 commit comments

Comments
 (0)