nbsp; char* str_reverse = str_reverst(str,' ');
printf("%s\n",str_reverse);
return 0;
}
5. 求母串中子串出现的次数
如"abcrtabc"中字串"abc"出现的次数是2。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//子串出现次数
int count(char* str, char *str_son){
if(*str=='\0'||*str_son=='\0'){return 0;}
char* s0, *s1;
int amount = 0;
while(*str!='\0'){
s0 = str; s1 = str_son;
while((*s0==*s1)&&(*s0!='\0')&&(*s1!='\0')){
s0++; s1++;
}
if(*s1=='\0'){
amount+=1;
}
str++;
}
return amount;
}
int main(){
char str[]="abcrtabc";
printf("%d\n",count(str,"abc"));
return 0;
}
6. 查找第一个匹配字串的起始位置
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//首个匹配字串的起始位置
int position(char* str,int n, char *str_son,int n_son){
if(*str=='\0'||*str_son=='\0'){return -1;}
if(n<=0||n_son<=0||n_son>n){return -1;}
int i=0;
for(;i<n-n_son;i++){
if(*str!=(*str_son)){
str++;
}
else{
for(int j=0;j<n_son;j++){
if(str[j]!=str_son[j]){
break;
}
}
return i;
}
}
return -1;
}
int main(){
char str[]="abcdefghigklmn";
printf("%d\n",position(str,strlen(str),"klm",strlen("klm")));
return 0;
}
7. 求两个字符串的最大公共子串
给定字符串A和B,输出A和B中的最大公共子串。比如A="aocdfe" B="pmcdfa" 则输出"cdf"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//两个字符串的最大公共字串(重要)
char* max_sub_str(char* str1,int str1_l, char* str2, int str2_l){
char* max_sub = (char*)malloc(100*sizeof(char));
char* max_sub_help = (char*)malloc(100*sizeof(char));
int p_str1,p_str2,p_str_help;
for(int i=0;i<str1_l;i++){ //最好先判断哪个str长
for(int j=0;j<str2_l;j++){
p_str1 = i;
p_str2 = j;
while(str1[p_str1]==str2[p_str2]){
max_sub_help[p_s