C++实现 Java String类的基本方法

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";
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值