C++——字符串处理
11、用字符数组存储和处理字符串
字符数组的声明和引用 字符串:
字符串常量 “china”,没有字符串变量,用字符数组来存放字符串,字符串以‘\0’结束。
字符串数组的初始化:
逐个输出输入字符串; 将整个字符串一次输入输出; 输出字符不包含\0; 输出字符串时用数组名,遇到\0结束; 输入多个字符串以空格分隔,输入单个字符串时期中不能有空格
|
static char str[8]={112,114,111,103,114,97,109,0};
static char str[8]={'p','r','o','g','r','a','m','\0'};
static char str[8]="program";
static char str[]="program";
#include<iostream>
using namespace std;
int main()
{
static char c[10]=
{'I',' ','a','m',' ','a',' ','b','o','y'}; //一维字符数组的声明和初始化
int i;
for(i=0;i<10;i++) //逐个输出字符数组的元素
cout<<c[i];
cout<<endl;
}//I’m a boy
//输出一个钻石图形
#include<iostream>
using namespace std;
int main()
{ //二维字符数组的声明和初始化,未被初始化的元素初始值为0:
static char diamond[][5]={{' ',' ','*'},{' ','*',' ','*'}, {'*',' ',' ',' ','*'},{' ','*',' ','*'}, {' ',' ','*'}};
int i,j;
for (i=0;i<5;i++) //逐个输出二维字符数组的元素
{
for(j=0;j<5 && diamond[i][j]!=0;j++)
cout<<diamond[i][j];
cout<<endl;
}
}
cin读取单词的时候遇到空格跳过;不能给数组名赋值,数组名时常量;
cin.getline(字符数组名st,字符个数N,结束符);
cin.get (字符数组名st,字符个数N,结束符);
一次连续读入多个字符,可以包括空格,直到读满N个,或者遇到结束符(默认为\n),读入的字符串存放在st中。
#include <iostream>
using namespace std;
void main (void)
{ char city[80];
char state[80];
int i;
for (i = 0; i < 2; i++)
{ cin.getline(city,80,',');
cin.getline(state,80,'\n');
cout<<"City: "<<city<<" State: "
<<state<<endl;
}
}
Beijing,China
City: Beijing Country: China
Shanghai,China
City: Shanghai Country: China
字符串处理函数:strcat(连接),strcpy(复制),strcmp(比较),strlen(求长度), strlwr(转换为小写),strupr(转换为大写),头文件<cstring>
在C++中用字符数组处理字符串有很多不方便,我们可以使用string类,
#include <string>
#include <iostream>
using namespace std ;
void trueFalse(int x)//辅助函数
{cout << (x? "True": "False") << endl;}
int main()
{ string S1="DEF", S2="123";
char CP1[]="ABC";
char CP2[]="DEF";
cout << "S1 is " << S1 << endl;
cout << "S2 is " << S2 << endl;
cout<<"length of S2:"<<S2.length()<<endl;
cout << "CP1 is " << CP1 << endl;
cout << "CP2 is " << CP2 << endl;
cout << "S1<=CP1 returned ";
trueFalse(S1<=CP1);
cout << "CP2<=S1 returned ";
trueFalse(CP2<=S1);
S2+=S1;
cout<<"S2=S2+S1:"<<S2<<endl;
cout<<"length of S2:"<<S2.length()<<endl;
}