Java作为当前主流编程语言,离不开其强大的类库。这里用c++实现其String类中几个常用的方法
-
charAt
class String{
public:
string str;
char charAt(int index);
};
char String:: charAt(int index){
if(index < str.length()){
return str[index];
} else {
return '-1';
}
}
-
codePointAt
class String{
public:
string str;
int codePointAt(int index);
};
int String:: codePointAt(int index){
return (int)str[index];
}
-
compareTo
class String{
public :
string str;
int compareTo(string strt);
};
int String::compareTo(string strt){
if(str > strt){
return 1;
}
else if(str == strt){
return 0;
} else {
return -1;
}
}
-
concat
class String{
public :
string str;
string concat(string strt);
};
string String::concat(string strt){
return str + strt;
}
-
contentEquals
class String{
public :
string str;
bool contentEquals(char* ch);
};
bool String::contentEquals(char* ch){
string strt = ch;
int i = 0, j = 0;
while(j != strt.length() && i < str.length()){
if(str[i] == strt[j]){
i++, j++;
} else {
i++, j = 0;
}
}
if(j == strt.length()) return true;
else return false;
}
-
copyValueOf
class String{
public :
string str;
string copyValueOf(char* ch);
};
string String::copyValueOf(char* ch){
for(int i = 0; i < str.length(); i++){
ch[i] = str[i];
}
return ch;
}
-
isEmpty
class String{
public :
string str;
bool isEmpty();
};
bool String::isEmpty(){
if(str.length() == 0){
return true;
} else {
return false;
}
}
-
Equals
int equals(string str1, string str2){
if(str1 == str2) return 1;
else return -1;
}
-
contains
int contain(string strm, string strt){
int i = 0, j = 0;
while(j != strt.length() && i < strm.length()){
if(strm[i] == strt[j]){
i++, j++;
}else{
i++, j = 0;
}
}
if(j == strt.length()) return 1;
else return -1;
}
-
indexof(char)
int indexof(string str, char ch){
int i = -1;
while(++i < str.length()){
if(str[i] == ch){
return i;
}
}
return -1;
}
如果不区分大小写可以将字符内容都转换成小写
string toSmall(string s){
for(int i = 0; i < s.length(); i++){
if(s[i] >= 'A' && s[i] <= 'Z')
s[i] += 32;
}
return s;
}
-
indexof(string)
int indexof(string str1, string str2){
int i = 0, j = 0;
while(i != str1.length() && j < str2.length()){
if(str1[i] == str2[j])
i++, j++;
else
j++, i = 0;
}
if(j == str2.length() && i != str1.length()) return -1;
else return j-str1.length();
}
-
substring
string substring(string str, int begin, int end){
string temp = "";
for(int i = begin; i < end; i++){
temp += str[i];
}
if(begin >= 0 && end < str.length() && begin <= end) return temp;
else return "Range -1";
}