花了一個多小時,終於把這些寫完了,貼貼出來和大家分享下,都是關於字符串操作的,不懂請留言,注釋都很清楚的
[cpp]
#include<stdio.h>
/**
字符串操作&重寫C系統一些字符串操作函數
strcpy strcmp strcat
*/
void strReplace(char *,char *,int ); //替換
char *strCopy(char *,const char *); //拷貝
int strCompare(char *,char *); //比較
char *strConcat(char *,char *); //拼接
void strConvert(char *); //倒置
int strLength(char *); //獲取長度
//調用函數
void strOperate()
{
char source[]="China";
char rep[]="ese";
//替換
puts("---------replace------------");
strReplace(source,rep,4);
puts(source);
//拷貝
puts("---------strcpy------------");
char distStr[10];
strCopy(distStr,"abcdefg");
puts(distStr);
//比較
puts("---------strcmp------------");
printf("%d\n",strCompare("ABCD","ABC"));
//獲取長度
puts("---------strlength------------");
printf("%d\n",strLength("ABCDe"));
//拼接
puts("---------strconcat------------");
char sc[30] = "Chinese";
strConcat(sc," FUCK Japanese");
puts(sc);
//倒置
puts("---------strconvert------------");
char s[] = "I love my homeland";
strConvert(s);
puts(s);
}
//替換 www.2cto.com
void strReplace(char *soucrStr,char *replaceStr,int pos)
{
while(pos>0&&*soucrStr!='\0')//pos>1為了防止指針後移,以至於不准確
{
soucrStr++;//把指針移到指定位置
pos--;
}
while(*soucrStr!='\0'&&*replaceStr!='\0')
{
*soucrStr = *replaceStr;//替換
soucrStr++;
replaceStr++;
}
}
//拷貝(目標字符數組要比源數組大,不然會溢出,產生各種悲劇)
char *strCopy(char *distStr,const char *sourceStr)
{
char *address = distStr;
while((*distStr++=*sourceStr++)!='\0');//先賦值比較再自加
//*distStr++是對指針++,再取值,至右向左,單獨測試過了
return address;
}
//比較
int strCompare(char *str1,char *str2)
{
while(*str1&&*str2&&(*str1==*str2))
{
str1++;
str2++;
}
return *str1-*str2;
}
//拼接
char *strConcat(char *distStr,char *sourceStr)
{
char *address = distStr;
while(*distStr)//移動到目標字符串尾部,若使用while(*distStr++),則會出錯
{
distStr++;
}
while((*distStr++=*sourceStr++)!='\0');
return address;
}
//倒置
void strConvert(char *str)
{
int len = strLength(str);
int mid = len/2;
char tmp;
for(int i=0;i<mid;i++)
{
tmp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = tmp;
}
}
//獲取長度
int strLength(char *str)
{
int len = 0;
while(*str++)
len++;
return len;
}