@quinn
2015-03-20T09:27:33.000000Z
字数 1992
阅读 1704
数据结构
C/C++基础
自己手动实现的字符串基本处理操作
索引数组版本 array_mode.h
//统计长度
int strlen1(const char s[])
{
int i;
for(i = 0; s[i] != 0; i++);
return i;
}
//Copy
char* strcpy1( char s2[], const char s1[])
{
int i;
for(i = 0; (s2[i] = s1[i]) != 0; i++);
return s2;
}
//Compare
int strcmp1(const char s1[], const char s2[])
{
int i = 0;
for (; s1[i] == s2[i]; i++)
{
if (s1[i] == 0) //s1[i], s2[i] 同时为0
{
return 0;
}
}
return s1[i] - s2[i];
}
//Compare first n characters
int strncmp1(const char s1[], const char s2[], int n)
{
int i = 0;
for (; s1[i] == s2[i]; i++)
{
if (s1[i] == 0 || (i+1) == n)
{
return 0;
}
}
return s1[i] - s2[i];
}
//追加
char* strcat1(char* s1, const char* s2)
{
int i = 0, j = 0;
for ( ; s1[i] != 0; i++);
for ( ; (s1[i] = s2[j]) != 0; i++, j++);
return s1;
}
指针版本 pointer_mode.h
//统计长度
int strlen2(const char* s)
{
int i = 0;
while(*s++)
i++;
return i;
}
//Copy
char* strcpy2( char *s2, const char *s1)
{
while ( *s2++ = *s1++);
return s2;
}
//Compare
int strcmp2(const char* s1, const char* s2)
{
while(*s1++ == *s2++)
{
if (*(s1-1) == 0) //s1[i], s2[i] 同时为 '\0'
{
return 0;
}
}
return *(s1-1) - *(s2-1);
}
//Compare first n characters
int strncmp2(const char* s1, const char* s2, int n)
{
while(*s1++ == *s2++)
{
n--;
if (*(s1-1) == 0 || n == 0) //s1[i], s2[i] 同时为 '\0'
{
return 0;
}
}
return *(s1-1) - *(s2-1);
}
//追加
char* strcat2(char* s1, const char* s2)
{
while(*s1++);
s1--;
while(*s1++ = *s2++);
return s1;
}
测试函数 main.cpp
#include<stdio.h>
#include <stdlib.h>
#include "array_mode.h"
#include "pointer_mode.h"
int main()
{
char str1[50] = "Hello,HIT";
char str2[30] = "Hello,SZIIT";
char str3[30], str4[30];
//计算字符串长度
printf("strlen1(str1) = %d\n", strlen1(str1));
printf("strlen2(str1) = %d\n", strlen2(str1));
//复制字符串
strcpy1(str3,str1);
printf("str3 = %s\n", str3);
strcpy2(str4,str1);
printf("str4 = %s\n", str4);
//比较
printf("strcmp1(str1, str2) = %d\n", strcmp1(str1, str2));
printf("strcmp1(str1, str3) = %d\n", strcmp1(str1, str3));
printf("strcmp2(str1, str2) = %d\n", strcmp2(str1, str2));
printf("strcmp2(str1, str3) = %d\n", strcmp2(str1, str3));
//前缀比较
printf("strncmp1(str1, str2) = %d\n", strncmp1(str1, str2, 6));
printf("strncmp2(str1, str2) = %d\n", strncmp2(str1, str2, 6));
//追加
strcat1(str1, "hehe");
printf("str1 = %s\n", str1);
strcat2(str1, "haha");
printf("str1 = %s\n", str1);
system("pause");
return 0;
}