一、案例内容
字符串的常见操作主要有创建,输出,查找指定字符或查找指定位置的字符、删除指定字符或删除指定位置的字符,在指定位置插入指定字符等。
二、案例代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 80
/*显示程序菜单*/
void menu()
{
printf("**************************\n");
printf(" 字符串操作演示程序\n");
printf("**************************\n");
printf(" 1.创建字符串\n");
printf(" 2.输出字符串\n");
printf(" 3.求串长\n");
printf(" 4.查找\n");
printf(" 5.插入\n");
printf(" 6.删除\n");
printf(" 0.退出\n");
printf("**************************\n");
}
/*创建字符串*/
void str_in(char str[])
{getchar();printf("\n请输入字符串:");gets(str);printf("\n请按任意键继续...\n");getchar();
}
/*输出字符串*/
void str_out(char *p)
{printf("\n原字符串是:");while(*p){ putchar(*p);p++;}printf("\n\n请按任意键继续...\n");getchar();
}
/*求字符串长度*/
int str_len(char str[])
{int i;for(i=0;str[i]!='\0';i++);return i;
}
/*在字符串中查找指定的字符*/
int str_search(char *p,char ch)
{if(str_len(p)==0){ printf("空串!\n");return 0;}else{ for(;*p!='\0';p++)if(*p==ch) break;if(*p) return 1;else return 0;}
}
/*在字符串中查找指定字符,如果没有则插入字符在串尾,否则不插入*/
void str_insert(char *p,char ch)
{if(str_search(p,ch))printf("\n串\"%s\"中有字符%c,不插入。\n",p,ch);else{while(*p!='\0') p++;*p=ch;*(++p)='\0';printf("\n已将字符%c插入到原串尾。\n",ch);}printf("\n请按任意键继续...\n");getchar();
}
/*删除字符串中指定的字符*/
void str_del(char *p,char ch)
{char *q=p;if(str_len(p)==0)printf("\n空串,无法删除!\n");else{for(;*p!='\0';p++)if(*p!=ch){ *q=*p;q++;}*q='\0';printf("\n已将原串中所有字符%c删除。\n",ch);}printf("\n请按任意键继续...\n");getchar();
}
//主函数
void main()
{int t;static char s[M];char *p=s,c;while(1){menu();printf("请选择一个操作:");scanf("%d",&t);switch(t){case 1: str_in(s);break;case 2: str_out(s);break;case 3: printf("\n串\"%s\"的长度是%d。\n",p,str_len(p));printf("\n请按任意键继续...\n");getchar();break;case 4: getchar();printf("\n请输入要查找的字符:");c=getchar();if(str_search(p,c))printf("\n串\"%s\"中有字符%c。\n",s,c);elseprintf("\n串\"%s\"中没有字符%c。\n",p,c);printf("\n请按任意键继续...\n");getchar();break;case 5: getchar();printf("\n请输入要插入的字符:");c=getchar();str_insert(p,c);break;case 6: getchar();printf("\n请输入要删除的字符:");c=getchar();str_del(s,c);break;case 0: exit(0);default: printf("输入错误!请按任意键后,重新选择!\n");getchar();}}
}
二、运行结果