/**
作者:一叶扁舟
时间:19:54 2017/6/7
作用:
有一个字符串符合以下特征(“abcd11111abcd2222abcdqqqqqabcd11111abcd2222abcdqqqqq abcd11111abcd2222abcdqqqqq”),
要求写一个函数(接口),输出以下结果
1)求字符串字串(“abcd”)出现的次数,并把结果传出;
2)把字符串替换成(dcba11111dcb2222dcqqqqqad11111dcba2222dcbqqqqq"),并把结果传出。
*/
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
void getTargetCount(char *src, char *target, int *count){
int num = 0;
char *p = src;
char temp[100];
int strLength = strlen(target);
char *q = src+strLength;
while (*p != '\0'){
memcpy(temp,p,strLength);
temp[strLength] = '\0';
if (strcmp(temp, target) == 0){//说明刨出来的字符串相等
num++;
p = p + strLength;
}else{
p++;
}
}
*count = num;
}
void replaceSubString(char *src, char *target, char *result){
int num = 0;
char *p = src;
char temp[100];
int strLength = strlen(target);
char *q = result;
while (*p != '\0'){
memcpy(temp, p, strLength);
temp[strLength] = '\0';
if (strcmp(temp, target) == 0){//说明刨出来的字符串相等
num++;
if (num % 4 == 0){
strcat(q, "a");
}else if (num % 4 == 1){
strcat(q,"dcba");
}else if (num % 4 == 2){
strcat(q, "dcb");
}else{
strcat(q, "dc");
}
p = p + strLength;
}
else{
char tempChar[2] = {0};
tempChar[0] = *p;
//注意在使用strcat时,tempChar必须指向内存的,即tempChar分配了空间temp是以‘\0’结尾
//
strcat(q, tempChar);
p++;
}
}
}
void main17(){
char *str = "abcd11111abcd2222abcdqqqqqabcd11111abcd2222abcdqqqqqabcd11111abcd2222abcdqqqqq";
int count = 0;
char result[100] = {0};
char *target = "abcd";
getTargetCount(str, target, &count);
printf("字符串:%s\n",str);
printf("目标子串:%s出现了%d次\n",target,count);
replaceSubString(str,target,result);
printf("替换后的字符串:%s\n",result);
system("pause");
}
c语言练习题(4)--字符串递减替换
最新推荐文章于 2023-02-19 09:16:46 发布