C语言中的处理字符串一般将其当做是以NULL或者\0结尾的字符数组char[n],在进行字符串的增删改查时需要用到标准库的一些函数,如strcopy,strstr等,C++中处理字符串除了兼容C语言的这种操作之外,其还封装了string类,专门用于处理字符串,并将字符串的操作方法也封装到string类当中,这种OOP的思想增强了数据的安全性也使得软件更加模块化。下面纪录一下string类的一些具体操作。
string类的初始化:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
/*字符串初始化*/
int main() {
string s1 = "1234";
string s2("aaaa");
string s3 = s2;
string s4(10, 'b');
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
system("pause");
return 0;
}
运行结果:
string类的遍历:
int main() {
string s1 = "1234";
for (int i = 0; i < s1.length(); i++) {
cout << s1[i] << ' ';
}
cout << endl;
for (int i = 0; i < s1.length(); i++) {
cout << s1.at(i) << ' ';//有异常检查
}
cout << endl;
for (string::iterator it = s1.begin(); it != s1.end(); it++) {
cout << *it <<' ';
}
cout << endl;
cout << s1 << endl;
system("pause");
return 0;
}
运行结果:
字符串转char[]:
int main() {
string s1 = "1234";
char buf[128] = { 0 };
s1.copy(buf,3);
printf("%s\n", buf);
cout << s1 << endl;
system("pause");
return 0;
}
运算结果:
字符串拼接:
int main() {
string s1 = "1234";
string s2 = "2345";
string s3 = "222";
s1 = s1 + s2;
s3.append(s1);
cout << s1 << endl;
cout << s3 << endl;
system("pause");
return 0;
}
运算结果:
字符串查找和替换
/*字符串查找替换分割*/
int main() {
string s1 = "hello world";
int count = 0;
int posi = s1.find('o',0);
while (posi != string::npos) {
//s1.replace(posi, 1, 1, 'O');
s1.replace(posi, 1, "O");
count++;
posi++;
posi = s1.find('o', posi);
}
cout << count << endl;
cout << s1 << endl;
system("pause");
return 0;
}
输出结果:
字符串删除和插入:
int main() {
string s1 = "hello world";
string::iterator it = find(s1.begin(),s1.end(),'o');
if (it != s1.end())
s1.erase(it);
cout << s1 << endl;
string s2 = "stephen";
s1.insert(3,s2);
cout <<"after insert:"<< s1 << endl;
system("pause");
return 0;
}
输出结果:
未完待续。。。。