1.strtok()函数:原型:char *strtok(char s[], const char *delim);
#include<stdio.h>
void StrCopy(char*pDest, char*pSoruce)//字符串复制,采用指针
{
while (*pDest=*pSoruce)
{
++pDest;
++pSoruce;
}
}
void StrCopy1(char*pDest, char*pSoruce)//字符串复制
{
while (*pDest++ = *pSoruce++);
}
void StrCat(char *pDest, char* pSource)//字符串追加,采用数组形式
{
int i = 0,j=0;
while (pDest[i])
++i;
while (pDest[i++] = pSource[j++]);
}
void StrCatt(char *pDes, char* pSource)//字符串追加,采用指针
{
while (*pDes)
++pDes;
while (*pDes++ = *pSource++);
}
int main()
{
char s1[50];
char s2[] = "hello";
StrCopy(s1,s2);
puts(s1);
StrCopy1(s1, s2);
puts(s1);
StrCat(s1,s2);
puts(s1);
StrCatt(s1, s2);
puts(s1);
return 0;
}
该函数目的和功能是:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针。
#include<stdio.h>
#include<string.h>
char str[] = "A string \t of , ,tokens\n and some more tokens";
char seps[] = " , \t\n";
char *token;
int main()
{
printf("Tokens:\n");
token = strtok(str,seps);
while (token!=NULL)
{
printf("%s\n",token);
token = strtok(NULL,seps);
}
return 0;
}
执行结果如下(VS2013)
2.strcpy/strcat函数(采用数组下标形式)
#include<stdio.h>
#include<string.h>
void StringCopy(char* pDest, char *pSourse)
{
//int i = 0;
//while (pSourse[i]!=0)
//{
// pDest[i++] = pSourse[i];
//}
//pDest[i] = pSourse[i];//0结尾赋值给目标函数,满足字符串结束要求
int i = -1;
do
{
pDest[++i] = pSourse[i];
} while (pSourse[i]);
}
int main()
{
char str[80];
/*strcpy(str,"hello world");
puts(str);
strcat(str,"xxx");*/
StringCopy(str,"hello");
puts(str);
return 0;
}
3.strcpy/strcat函数(采用指针标形式)
#include<stdio.h>
void StrCopy(char*pDest, char*pSoruce)//字符串复制,采用指针
{
while (*pDest=*pSoruce)
{
++pDest;
++pSoruce;
}
}
void StrCopy1(char*pDest, char*pSoruce)//字符串复制
{
while (*pDest++ = *pSoruce++);
}
void StrCat(char *pDest, char* pSource)//字符串追加,采用数组形式
{
int i = 0,j=0;
while (pDest[i])
++i;
while (pDest[i++] = pSource[j++]);
}
void StrCatt(char *pDes, char* pSource)//字符串追加,采用指针
{
while (*pDes)
++pDes;
while (*pDes++ = *pSource++);
}
int StrCmpp(char s1[], char s2[])
{
int i = 0;
while (s1[i]&&s2[i])
{
if (s1[i] > s2[i])
return 1;
if (s1[i] , s2[i])
return -1;
++i;
}
return 0;
}
int StrCmp(char*pDest, char* pSorue)//采用数组
{
unsigned char *p1 = (unsigned char *)pDest;
unsigned char *p2 = (unsigned char* )pSorue;
int i = 0;
while (p1[i] && p1[i] == p2[i])
i++;
return p1[i]-p2[i];
}
int StrCmppp(char*pDest, char* pSorue)//采用纯指针
{
unsigned char *p1 = (unsigned char *)pDest;
unsigned char *p2 = (unsigned char*)pSorue;
while (*p1 && *p1 == *p2)
++p1, ++p2;
return *p1 - *p2;
}
int main()
{
char s1[50];
char s2[] = "2";
char s3[] = "1";
StrCopy(s1,s2);
puts(s1);
StrCopy1(s1, s2);
puts(s1);
StrCat(s1,s2);
puts(s1);
StrCatt(s1, s2);
int n = StrCmppp(s3,s2);
if (n>0)
{
puts("前面大");
}
if (n<0)
{
puts("后面大");
}
if (n==0)
{
puts("前后一样大");
}
return 0;
}