C++常用字符串处理函数及使用示例
char *strcpy(char *s1, const char *s2)
将字符串s2复制到字符串数组s1中,返回s1的值
char *strncpy(char *s1, const char *s2, size_t n)
将字符串s2中最多n个字符复制到字符串数组s1中,返回s1的值
char *strcat(char *s1, const char *s2)
将字符串s2添加到字符串s1的后面。s2的第一个字符重定义s1的null终止符。返回s1的值
char *strncat(char *s1, const char *s2, size_t n)
将字符串s2中最多n个字符添加到字符串s1的后面。s2的第一个字符重定义s1的null终止符。返回s1的值
int strcmp(const char *s1, const char *s2)
比较字符串s1和字符串s2。函数在s1等于、小于或大于s2时分别返回0、小于0或者大于0的值
int strncmp(const char *s1, const char *s2, size_t n)
比较字符串s1中的n个字符和字符串s2。函数在s1等于、小于或大于s2时分别返回0、小于0或者大于0的值
char * strtok(char *s1,const char *s2)
用一系列strtok调用将s1字符串标记化(将字符串分成各个逻辑组件,如同一行文本中的每个单词),用字符串s2所包含的字符分隔。 首次调用时包含s1为第一个参数,后面调用时继续标记化同一字符串,包含NULL为第一个参数。每次调用时返回当前标记指针。如果函数调用时不再有更多标记,则返回NULL
size_t strlen(const char *s)
确定字符串长度,返回null终止符之前的字符数
使用示例:
//源代码在Visual c++6.0环境下编译通过
#include <iostream.h>
#include <string.h>
int main()
{
char str1[50] = "Happy birthday to ", str2[] = "coffeehu";
char temp1[100],temp2[6], * temp;
char str[] = "This is a sentence with 7 tokens";
strcpy(temp1, str1);
strncpy(temp2, str1, 5);
temp2[5] = '/0';
cout << "strcpy result: " <<temp1 << "/n";
cout << "strncpy result: " << temp2 << "/n";
cout << "strcat result: " << strcat(str1, str2) << "/n";
cout << "strncat result: " << strncat(str1, str2, 6) <<"/n";
cout << "strcmp result: " << strcmp(temp2,"Happ") <<"/n";
cout << "strncmp result: " << strncmp(str1,"Happy",5) <<"/n";
//strtok function eg.
temp = strtok(str, " ");
while(temp != NULL)
{
cout << temp <<'/n';
temp = strtok(NULL, " ");
}
cout << "strlen result: " << strlen(str2) <<"/n";
return 0;
}
--------------------------------
C 语言中操作字符串的一些函数源代码 | |
很多人认为C语言中的难点是指针,对指针的理解直接关系到所编程序的好坏,所以, 在这里列举了一些C编译器通常都有的标准函数的源代码,看过它们,就能对指针和字符串 有所了解了. 1. strlen(),计算字符串长度 int strlen(const char string) { int i=0; while(string[i]) i++; return i; } 2. strcpy(), 字符串拷贝. char *strcpy(char *destination, const char *source) { while(*destinaton++=*source++); return (destination-1); } 3. strcat(), 字符串的连接. char *strcat(char *target,const char *source) { char *original=target; while(*target) target++; // Find the end of the string while(*target++=*source++); return(original); } 4. streql(), 判断两个字符串是否相等. int streql(char *str1,char *str2) { while((*str1==*str2)&&(*str1)) { str1++; str2++; } return((*str1==NULL)&&(*str2==NULL)); } 5. strchr(), 在字符串中查找某个字符. char *strchr(const char *string,int letter) { while((*string!=letter)&(*string)) string++; return (string); } 6. chrcnt(), 计算某个字符在字符串中出现的次数. int chrcnt(const char *string,int letter) { int count=0; while(*string) if(*string==letter)count++; return count; } 7. strcmp(), 判断两个字符串是否相等. int strcmp(const char *str1,const char *str2) { while((*str1==*str2)&&(*str1)) { str1++; str2++; } if((*str1==*str2)&&(!*str1)) //Same strings return o; else if((*str1)&&(!*str2)) //Same but str1 longer return -1; else if((*str2)&&(!*str1)) //Same but str2 longer else return((*str1>*str2)?-1:1); } |