可以用C语言字符串数组的形式读取字符串,也可以使用string类型读取字符串。使用string好处:字符串相关内存可以被自动管理,而C语言字符串要先声明足够大存储空间才能读入字符串。 (string 最大特点就是易于管理)
例:
#include <iostream>
#include <string>
using namespace std;
void main()
{
string str;
cin>>str;
cout<<str<<endl;
}
分析:此时头文件必须得像上面这么写,如写成
#include <iostream.h>
#include <string.h>
而不用using namespace std;则编译不通过。
以后想要操作字符串就可以直接用string类型定义拉,省得定义个字符数组或者字符串指针(必要时还是用用,呵呵)。
字符串函数使用起来比字符指针简单好用,不需设置存储空间,系统自动开辟。
String 的另一种用法,是用n个字符初始化字符串s=string(int n,char c),然后使用流状态函数配合循环完成菱形输出。例:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
char c;
cin.get (c);
int i;
for(i =0;i<10;i++)
{
cout<<string(9-i,' ')<<string(i,c);
if(i>=1)
cout<<string(i-1,c)<<endl;
else
cout<<endl;
}
for(i=9;i>=0;i--)
{
cout<<string(9-i,' ')<<string(i,c);
if(i>=1)
cout<<string(i-1,c)<<endl;
else
cout<<endl;
}
return 0;
}
字符串操作
最新推荐文章于 2024-02-19 14:23:09 发布