ToNgBosmile
ToNgBosmile
采纳率100%
2017-12-04 11:32 阅读 641

急!!!!!!!!!

编写一个函数,将指定字符串内的某字符串替换为另外的字符串,要求代码具有安全检查,健壮性

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    lijiajunbuaa lijiajunbuaa 2017-12-05 01:16
    点赞 评论 复制链接分享
  • LiFangHui_ 芳辉啊 2017-12-05 04:28

    #include #include int checkStr(char *s1, char *s2) {//匹配字符串相不相等 for (int i = 0; i < strlen(s2); i++) { if (s1[i] != s2[i]) return 0; } return 1; } void reStr(char *s1, char *s2, char *s3) {//替换字符串 int s1len = strlen(s1), s2len = strlen(s2), s3len = strlen(s3); int n1 = s1len - s2len; int n2 = s2len - s3len; if (n2 > 0) { //后面的字符串全部向前移n2个位置 for (int i = s2len; i < s1len; i++) { s1[i - n2] = s1[i]; } s1[s1len - n2] = '\0'; } else if (n2 < 0) { //后面的字符串全部向后移n2个位置 for (int i = s1len; i >= s2len; i--) { s1[i - n2] = s1[i]; } s1[s1len - n2 + 1] = '\0'; } //然后在把要替换的字符串插进去 for (int i = 0; i < s3len; i++) { s1[i] = s3[i]; } } int replaceStr(char *s1, char *s2, char *s3) {//替换字符串函数返回n表示替换了多少次 int n = 0; for (int i = 0; i < strlen(s1); i++) { if (s1[i] == s2[0] && checkStr(&s1[i], s2) == 1) { reStr(&s1[i], s2, s3); n++; } } return n; } int main() { // test!!! char s1[30] = "qwertyuerp"; char s2[] = "er"; char s3[] = "111111"; printf("%d\n%s\n", replaceStr(s1, s2, s3), s1); return 0; }

    点赞 评论 复制链接分享

相关推荐