2013年华为c语言上机试题3
2015-11-05 01:26
609 查看
C++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | //2013年华为c语言上机试题3 //对源字符串中得字符串进行查找替换 //并返回动态申请空间的指针 char* Fun(char* pSrc, char* pOldStr, char* pNewStr); #include<stdio.h> #include<stdlib.h> char*change(char*s1, char*s2, char*s3) { int L_s1 = 0; //源字符串长度 int L_s2 = 0; //要被替换的字符串的长度 int L_s3 = 0; //替换的字符串的长度 char*restr; //指向替换后的字符串 int position = 1; //旧字符串在源字符串中的位置 int i = 0, j = 0, k = 0; //求各个字符串的长度 for(i = 0;s1[i] != '\0';i++) { L_s1++; } for(i = 0; s2[i] != '\0'; i++) { L_s2++; } for(i = 0; s3[i] != '\0'; i++) { L_s3++; } restr = (char*)malloc(L_s1 - L_s2 + L_s3 + 1); //开辟一个存放新的字符串的内存空间 i = 0; //计算出旧字符串在源字符串中的位置 while(s1[i] != '\0' && s2[j] != '\0') { if(s1[i] == s2[j]) { i++; j++; } else if(s1[i] == s2[0]) { position = i + 1; i++; j = 1; } else { position = i + 2; i++; j = 0; } } if(s2[j] == '\0') position = position; else { position = 0; //没有查找到元字符串 return NULL; } //替换字符串 i = 0; j = 0; while(s1[i] != '\0') { if(i == (position - 1)) { while(s3[j] != '\0') { restr[k] = s3[j]; j++; k++; } i = i + L_s2; } else { restr[k] = s1[i]; k++; i++; } } restr[k] = '\0'; return restr; } void main() { char*sStr = "chenweiwei"; char*oStr = "wei"; char*newStr = "you"; char*pStr; printf("元字符串为\n"); printf("%s\n", sStr); printf("要被替换的字符串为\n"); printf("%s\n", newStr); pStr = change(sStr, oStr, newStr); printf("替换后的字符串为\n"); printf("%s\n", pStr); free(pStr); } |
相关文章推荐
- C++设计模式-Adapter适配器模式
- c++中的强制转换static_cast、dynamic_cast、reinterpret_cast的不同用法儿
- 一维数组的函数调用
- C++设计模式-Singleton
- C++中基类私有成员会被继承吗
- C++中基类私有成员会被继承吗
- C++设计模式-Observer观察者模式
- C++ 二叉树 叶子节点
- C++string类型成员函数实现
- C++,二叉树,叶子节点
- C++ Primer中文版(第五版)——第六章 函数
- C++基础——bitset与vector<bool>
- 最全的c++map的用法
- C语言基础问题
- C++基础---友元类
- C++基础——bitset与string的相互转化
- 用C++/CLI搭建C++和C#之间的桥梁(二)—— 基本语法
- 转载:C++11尝鲜:std::move和std::forward源码分析
- 爬爬爬之路:OC语言(八) 属性 KVC简单介绍
- c++对文件操作