思路是重载下标运算符,比较简单,详细见代码
#include <iostream>
#include <string>
using namespace std;
class words{
int len;
char *str;
public :
int getlen(){return len;}
words(char *s){
str=new char[strlen(s)+1];
strcpy(str,s);
len=strlen(str);
}
~words(){
delete str;
}
char operator [](int n){
static char ch;
if(n>len-1){
cout<<"out of the table"<<endl;
return ch;
}else
return *(str+n);
}
void disp(){
cout<<str<<endl;
}
};
void main(){
words word("time devour all things !");
word.disp();
cout<<"the length of the string is "<<word.getlen()<<endl;
for(int i=0;i<25;i++)
cout<<word[i]<<" ";
cout<<endl;
while(1);
}
C++字符串类操作实现
本文介绍了如何通过重载下标运算符实现C++中字符串类的操作,包括获取字符串长度、展示字符串内容以及通过循环遍历字符串元素。
2345

被折叠的 条评论
为什么被折叠?



