//实现两个字符串复制
char* strcpy_(char* strS, char* strT){
char* temp = strT;
if(strS==NULL||strT==NULL){return NULL;}
while((*temp++=*strS++)!='\0');
return strT; //返回的是字符串首地址
}
int main(){
char strS[6]="12345";
char strT[6];
char* ss;
ss = strcpy_(strS,strT);
printf("%s\n\n",ss);
printf("%s\n",strT);
return 0;
}
3. 字符串循环右移n位
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//字符串循环移动n位
char* strCir(char* str, int n){
int length = strlen(str);
char* temp=(char*)malloc(length+1);
n =n%length;
for(int i=0;i<length;i++){
int move = i+n;
if(move>=length){
move=move%length;
}
temp[move]=str[i];
}
temp[length]='\0';
return temp; //返回的是字符串首地址
}
int main(){
char str[]="ABCDEFG12345";
char* str_right = strCir(str,8);
printf("%s\n\n",str);
printf("%s\n",str_right);
free(str_right); //记得释放malloc内存
return 0;
}
4. 字符串逆序,以单词为单位逆序
如给定字符串“This is a sentence”,转换成"sentence a is This"。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//反转区间字符串
void reverse_Str(char* left, char* right){
while(left<right){
char temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
//字符串以单词为单位逆序
char * str_reverst(char * str, char key){
if(str==NULL){return str;}
char* start=str, *end=str, *kstr=str;
while((*++end)!='\0');
end--;
reverse_Str(start,end); //整个字符串逆序
while(*start!='\0'){
if(*start==key){
reverse_Str(kstr,start-1); //对中间单词逆序
kstr=start+1;
}
start++;
}
reverse_Str(kstr,start-1); //对最后一个单词逆序
return str;
}
int main(){
char str[45]="ABC DE FG B HIGK";
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>