编程中,常用到字符串的各个函数,总结如下:
1、字符串的初始化
1)char ch[5]={0}; //字符串,不是字符数组
2)char ch[5]={'\0'}; //字符串,不是字符数组,因为‘\0’与0等价。
3)char ch[5]=""; //字符串,不是字符数组
4)char *ch = ""; //很明显的字符串
2、字符串的复制
1)strcpy()
char ch[5];
char *str ="hao";
strcpy(ch,str);
2)strncpy()
Copy a string, to a maximum length
Synopsis:
#include <string.h>
char* strncpy( char* dst,
const char* src,
size_t n );
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
char buffer[15];
printf( "%s\n", strncpy( buffer, "abcdefg", 10 ) );
printf( "%s\n", strncpy( buffer, "1234567", 6 ) );
printf( "%s\n", strncpy( buffer, "abcdefg", 3 ) );
printf( "%s\n", strncpy( buffer, "*******", 0 ) );
return EXIT_SUCCESS;
}
produces the output:
abcdefg
123456g
abc456g
abc456g
strncpy()函数相比较strcpy()函数可以精确的控制拷贝几个字符。
3、字符串比较大小
char ch[]=“hello”;
char str[]="hello";
1)strcmp(ch,str);二者相等则返回0;ch小于str返回负值,ch大于str返回正值。//比较整个字符串的大小
2)int strcmp(char *str1,char * str2,int n)//比较两个字符串前n个字符的大小
当str1<str2时,返回值<0; 当str1=str2时,返回值=0; 当str1>str2时,返回值>0
4、c++中的string与c语言中的字符串进行转换
1)string str= "hello";
const char *ch = str.c_str();
倘若是Qt中的QString,需要先将QString转换为string
QString qstr = "world";
string str = qstr.toStdString()
2)char *ch="hello";
std::string str(ch);//c++可以直接将c语言的字符串转化为string
std::string str=ch;
5、其他类型的数据与字符串的转换
char ch[]=“8000”;
1)int i=atoi(ch);----->常用,因为是c语言函数,没有类的概念,所以注意函数用法。
2)long int j = atol(ch);
3)double f= atof(ch);------>常用,因为是c语言函数,没有类的概念,所以注意函数用法。
4)char str[4]= {0};
sprintf(str,"%d",100);//将数字100转换为十进制,再转化为字符串
sprintf(str,"%x",100);//将数字100转换为十六进制,再转化为字符串
6、字符串的长度
char str[3] = "ni";
strlen(str);//值为2,不包含‘\0’的所有字符的个数。
注意:与单目运算符sizeof()的区别,sizeof()是获取整个字符数组的大小!!!
7、字符串的拼接 //非字符串类型的数据及字符串数据拼接 //非字符串数据转换为字符串
#include <stdio.h>
int sprintf( char* buf,
const char* format,
... );
8、检索字符是否在字符串中
char *strchr(const char *str, int c)
返回一个指向该字符串中第一次出现的字符的指针,如果字符串中不包含该字符则返回NULL空指针
9、检索字符串是否存在子串
#include <string.h>
char* strstr(char* str,
char* substr );
返回一个指向该字符串中第一次出现的substr子串的指针,如果字符串中不包含该子字符串则返回NULL空指针