字符串操作,用两个例子来说明。
例程一:(付下载)
#include <stdio.h>
#include <string.h>
//打印字符串
void display(char name[],char ch[]);
void main()
{
charch1[40]="hello world";
charch2[40]="I love you";
intlen = 0;
intflag = 0;
charch[10];
display("ch1= " ,ch1);//打印字符串
display("ch2= " ,ch2);//打印字符串
/*********************************求长度函数*******************************/
len= strlen(ch1); //把ch2的数据拷贝到ch1
printf("len= %d \n",len);
/**************************************************************************/
/*********************************比较函数**********************************/
flag= strcmp(ch1,ch2);
printf("flag= %d \n",flag);
/**************************************************************************/
/*********************************截取字符函数*****************************/
//strchr(ch1,'w');//从w开始查找,返回字符串
display("截取的字符串 :" ,strchr(ch1,'w'));//打印字符串
/**************************************************************************/
/*********************************查找字符函数*****************************/
display("查找的字符串 :" ,strstr(ch1,"world"));//打印字符串
/**************************************************************************/
/*********************************截取字符函数*****************************/
//cout<<strpbrk(ch1,"l")<<endl;
display("从l开始截取字符串 :" ,strpbrk(ch1,"l"));//从l开始截取字符串
/**************************************************************************/
printf("在\"he\"中查找属于ch1集合的元素的个数:%d\n",strspn(ch1,"he"));
/*********************************附加函数**********************************/
strcat(ch1,ch2);//把ch2的数据拷贝到ch1
display("ch1= " ,ch1);//打印字符串
/****************************************************************************/
/*********************************拷贝函数************************************/
strcpy(ch1,ch2);//把ch2的数据拷贝到ch1
display("ch1= " ,ch1);//打印字符串
/****************************************************************************/
}
//打印字符串
void display(char name[],char ch[])
{
char*p,*q;
p=ch;
q=name;
//先打印name
while(*q!='\0')
{
printf("%c",*q++);
}
//再打印ch
while(*p!='\0')
{
printf("%c",*p++);
}
//换行
printf("\n");
}
例程二:(付下载)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void main()
{
charch1[]="4.56";
intinter;
floatflo;
doubledou;
inter= atoi(ch1);//字符串转换为整型,并取整
printf("inter= %d \n",inter);
flo= atof(ch1);//字符串转换为float
printf("flo= %f \n",flo);
dou= atof(ch1);//字符串转换为double
printf("dou= %lf \n",dou);
if(isalpha('a'))//检查是否为字母字符
{
printf("是字母\n");
}
if(isupper('A'))//检查是否为大写字母字符
{
printf("是大写字母\n");
}
if(islower('a'))//检查是否为小写字母字符
{
printf("是小写字母\n");
}
if(isdigit('5'))//检查字符是否为数字
{
printf("字符是数字\n");
}
if(isxdigit(0x34))//检查是否为十六进制数字表示的有效字符
{
printf("是十六进制有效字符\n");
}
if(isspace(' '))//检查是否为空格类型字符
{
printf("是空格类型字符\n");
}
printf("%x:%s\n",0x0a,iscntrl(0x0d)?"yes":"no");//检查是否为控制字符
if(ispunct(','))//检查是否为标点符号
{
printf("是标点\n");
}
if(isalnum('4g'))//检查是否为字母和数字
{
printf("是字母和数字\n");
}
if(isprint('d'))//检查是否是可打印字符
{
printf("是可以打印的字符\n");
}
if(isgraph('s'))// 检查是否是图形字符,等效于 isalnum() | ispunct()
{
printf("是图形字符\n");
}
}