运行结果:
完整代码:
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <string.h> 5 6 void replaceAll(char *ppstr, char *from, char *to) 7 { 8 //备份地址 9 //首地址,用于被赋值 10 char *start1 = ppstr; 11 //游标,用于给start1赋值 12 char *start2 = ppstr; 13 //求出要被转换的字符串和要被转成的字符串长度,分三种情况讨论 14 int length1 = strlen(from); 15 int length2 = strlen(to); 16 //如果要替换的字符串长度和原来的相等 17 if (length1 == length2) 18 { 19 while ((*start1 = *start2) != ‘\0‘) 20 { 21 //假定找到子串 22 int flag = 1; 23 //判断是否找到子串 24 for (int i = 0; i < strlen(from); i++) 25 { 26 if (start2[i] != from[i] || start2[i] == ‘\0‘) 27 { 28 flag = 0; 29 break; 30 } 31 } 32 33 //如果没找到子串,被赋值的地址自增,游标自增 34 if (flag == 0) 35 { 36 start1++; 37 start2++; 38 } 39 else//如果找到了,则进行替换 40 { 41 //start2 += length1;//删除 42 //赋值 43 for (int i = 0; i < length1; i++) 44 { 45 start1[i] = to[i]; 46 } 47 //前进 48 start1 += length1; 49 start2 += length1; 50 } 51 } 52 } 53 //如果要替换的字符串长度大于原来的长度 54 else if(length1 < length2) 55 { 56 while ((*start1 = *start2) != ‘\0‘) 57 { 58 //假定相等 59 int flag = 1; 60 for (int i = 0; i < strlen(from); i++) 61 { 62 if (start2[i] != from[i] || start2[i] == ‘\0‘) 63 { 64 flag = 0; 65 break; 66 } 67 } 68 69 if (flag == 0) 70 { 71 start1++; 72 start2++; 73 } 74 else 75 { 76 //start2 += length1;//删除 77 //求出差距 78 int chaju = length2 - length1; 79 //整体向后移动,留出空位 80 for (char *ptemp = ppstr + strlen(ppstr); ptemp >= start1 + length1; ptemp--) 81 { 82 *(ptemp + chaju) = *ptemp; 83 } 84 //把空位填充数据 85 for (int i = 0; i < length2; i++) 86 { 87 start1[i] = to[i]; 88 } 89 //游标和地址移动 90 start1 += length2; 91 start2 += length2; 92 } 93 } 94 } 95 //如果要替换的字符串长度小于原来的长度 96 else if (length1 > length2) 97 { 98 while ((*start1 = *start2) != ‘\0‘) 99 { 100 //假定相等 101 int flag = 1; 102 for (int i = 0; i < strlen(from); i++) 103 { 104 if (start2[i] != from[i] || start2[i] == ‘\0‘) 105 { 106 flag = 0; 107 break; 108 } 109 } 110 111 if (flag == 0) 112 { 113 start1++; 114 start2++; 115 } 116 else 117 { 118 //start2 += length1;//删除 119 //赋值 120 int chaju = length1 - length2; 121 //整体向前移动,压缩数据 122 for (char *ptemp = start1 + length2; *ptemp != ‘\0‘; ptemp++) 123 { 124 *ptemp = *(ptemp + chaju); 125 if (*(ptemp + chaju) == ‘\0‘) 126 { 127 break; 128 } 129 } 130 131 //填充 132 for (int i = 0; i < length2; i++) 133 { 134 start1[i] = to[i]; 135 } 136 137 //游标和地址移动 138 start1 += chaju; 139 start2 += chaju; 140 } 141 } 142 } 143 144 145 } 146 147 void main() 148 { 149 char str[100] = "我爱中国 我爱南京 我爱上海 我爱家庭"; 150 char from[10] = "我"; 151 char to[10] = "我和你"; 152 printf("原数据:%s\n", str); 153 printf("要被替换的数据:%s\n", from); 154 printf("替换成:%s\n", to); 155 replaceAll(str, from, to); 156 printf("替换后的数据:%s\n", str); 157 getchar(); 158 }
原文地址:https://www.cnblogs.com/xiaochi/p/8365411.html
时间: 2024-10-31 14:26:50