字符串处理
- 功能描述:从键盘输入一个文本行后,为用户提供菜单选择,实现字符串一些操作——显示文本行、查找并替换指定子串、删除指定子串、统计指定子串数目。
- 实现代码:
1 #include<stdio.h>
2 #include<string.h>
3 #include<stdlib.h>
4 #pragma warning(disable:4996)
5
6 #define NUM 256
7
8 void displayMenu();
9 int choiceItem();
10 void searchReplace(char *buf, char *s, char *t);
11 void deleteString(char *buf, char *s);
12 int totle(char *buf, char *s);
13
14 main()
15 {
16 char buf[NUM];
17 char s[80], t[80];
18 int choice;
19
20 system("cls");
21 printf("Enter a text line : "); /*输入待操作文本行*/
22 gets(buf);
23 do{
24 choice = choiceItem(); /*选择菜单项*/
25 switch (choice){
26 case 1:
27 printf("Search:");
28 gets(s);
29 printf("
Replace:");
30 gets(t);
31 searchReplace(buf, s, t);
32 printf("
The result is %s
", buf);
33 break;
34 case 2:
35 printf("
Delete:");
36 gets(s);
37 deleteString(buf, s);
38 printf("
The result is %s
", buf);
39 break;
40 case 3:
41 printf("
Search:");
42 gets(s);
43 printf("
The counts of %s is %d
", s, totle(buf, s));
44 break;
45 case 4:
46 printf("
The string is %s
", buf);
47 break;
48 }
49 } while (choice != 0);
50 printf("
Bey!");
51 }
52
53 void displayMenu() /*显示菜单*/
54 {
55 printf("
==========MENU===========
");
56 printf("1............Search/Replace");
57 printf("
2............Delete");
58 printf("
3............Totle");
59 printf("
4............Display");
60 printf("
0............Exit
");
61 printf("
Choice:
");
62 }
63
64 int choiceItem() /*菜单选择*/
65 {
66 int choice;
67 char line[80];
68
69 do{
70 displayMenu();
71 gets(line);
72 choice = atoi(line); /*将字符串转化为整型*/
73 } while (choice<0 || choice>4);
74 return choice;
75 }
76
77 void searchReplace(char *buf, char *s, char *t) /*查找替换子串*/
78 {
79 char m[256]; /*内部缓冲区*/
80 char *searchPtr = NULL;
81 do{
82 searchPtr = strstr(buf, s); /*查找子串*/
83 if (searchPtr != NULL){
84 strcpy(m, searchPtr + strlen(s)); /*将子串后面的字符串备份到m中*/
85 strcpy(searchPtr, t);
86 strcpy(searchPtr + strlen(t), m);
87 }
88 } while (searchPtr != NULL);
89 }
90
91 void deleteString(char *buf, char *s) /*删除子串*/
92 {
93 char *searchPtr = NULL;
94 do{
95 searchPtr = strstr(buf, s); /*查找子串*/
96 if (searchPtr != NULL){
97 strcpy(searchPtr, searchPtr + strlen(s));
98 }
99 } while (searchPtr != NULL);
100 }
101
102 int totle(char *buf, char *s) /*统计子串出现的次数*/
103 {
104 int n = 0;
105 char *searchPtr = NULL;
106 do{
107 searchPtr = strstr(buf, s); /*查找子串*/
108 if (searchPtr != NULL){
109 n++;
110 buf = searchPtr + strlen(s); /*改变查找的初始位置*/
111 }
112 } while (searchPtr != NULL);
113 return n;
114 }