1.atoi的头文件
atoi(将字符串转换成整型数)
相关函数 atof,atol,atrtod,strtol,strtoul
头文件 #include<stdlib.h>
定义函数 int atoi(const char *nptr);
函数说明 atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。
当我们定义string s1; 必须atoi(s1.c_str()),因为s1不是指针类型。
2.c_str()的含义
c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同。
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针 比如:最好不要这样:
char* c;
string s="1234";
c = s.c_str(); //c最后指向的内容是垃圾,
因为s对象被析构,其内容被处理应该这样用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作
c_str() 以 char* 形式传回 string 内含字符串。如果一个函数要求char*参数,可以使用c_str()方法:
string s = "Hello World!";
printf("%s", s.c_str()); //输出 "Hello World!
3.字符串分割
用strtok函数进行字符串分割
原型: char *strtok(char *str, const char *delim);
功能:分解字符串为一组字符串。
参数说明:str为要分解的字符串,delim为分隔符字符串。
返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。
示例:
01 |
//借助strtok实现split |
02 |
#include <string.h> |
03 |
#include <stdio.h> |
04 |
|
05 |
int main() |
06 |
{ |
07 |
char s[] = "Golden Global View,disk * desk" ; |
08 |
const char *d = " ,*" ; |
09 |
char *p; |
10 |
p = strtok (s,d); |
11 |
while (p) |
12 |
{ |
13 |
printf ( "%s\n" ,p); |
14 |
p= strtok (NULL,d); |
15 |
} |
16 |
|
17 |
return 0; |
18 |
} |
运行效果: