1.实现方法 compareTo, 能够实现按照字典序比较字符串大小
public class MyString{
public int compareTo(String s1, String s2){
//先将两个字符串的长度统一,进行逐个比较
int shortLen = 0;
if(s1.length() < s2.length()){
shortLen = s1.length();
} else{
shortLen = s2.length();
}
//进行同长度之间的比较
for(int i = 0; i < shortLen; i++){
if(s1.charAt(i) < s2.charAt(i)){
return -1;
}
if(s1.charAt(i) > s2.charAt(i)){
return 1;
}
}
//字符都相等的情况:
//1.同长度
if(s1.length() == s2.length()) return 0;
//2.不同长度
return s1.length() < s2.length() ? -1 : 1;
}
2.实现方法 contains, 能够判定字符串中是否包含子串
public class MyString{
public boolean contains(String str, String s){
//寻找相同的首字母
int count = 0;
for(int i = 0; i < str.length(); i++){
//找到了相同的首字母,开始逐个比较
if(str.charAt(i) == s.charAt(0)){
//更新count的值,防止上次在代码块中已经被修改
count = 0;
for(int j = 0; j < s.length(); j++){
//判定str始终比子字符串长,否则直接返回false
if(i + j < str.length()){
if(str.charAt(i+j) != s.charAt(j)){
break;
}
count++;
}
}
if(count == s.length()) return true;
}
}
return false;
}
}
3.实现方法 indexOf, 能够找出字符串子串存在的位置
public class MyString{
public int indexOf(String s1, String s2){
int count = 0;
int i = 0;
int j = 0;
for(i = 0; i < s1.length(); i++){
if(s1.charAt(i) == s2.charAt(0)){
count = 0;
for(j = 0; j < s2.length(); j++){
if(i + j < s1.length()) {
if (s1.charAt(i + j) != s2.charAt(j)) {
break;
}
count++;
}
}
//是的话,返回初始的索引值
if(count == s2.length()){
return i;
}
}
}
return -1;
}
}