先上代码:
ngnsvr9 [** NONE **]/home/xionghailong/c++/string $ cat string.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
int i=0;
int cat_find = 0;
cout<< "please enter a line of text: ";
getline( cin, input, '\n');//以换行符作为输入的结束,输入一行字符串
cout << "you have typed in the line"<<'\n'<<input<<'\n';
for (int i=0; i <input.length();
i++)
{
cout<< input[i] << '\n';// 字符串单个单个的打印
}
for(i = input.find("cat", 0); i != string::npos; i = input.find("cat", i) )// 查找字符串中是否有cat
{
cat_find++;
i++;
}
cout << "the word cat find"<< cat_find<< "in the string"<<':'<<'\n'<<input<<'\n';
}
执行结果:
ngnsvr9 [** NONE **]/home/xionghailong/c++/string $ g++ string.cpp
ngnsvr9 [** NONE **]/home/xionghailong/c++/string $ ./a.out
please enter a line of text: there is a cat
you have typed in the line
there is a cat
t
h
e
r
e
i
s
a
c
a
t
the word cat find1in the string:
there is a cat
代码中包含啦一些字符串的操作的接口,在实际代码中很有帮助。