strtok的用法
函数原型:char *strtok(char *s, char *delim);
函数功能:把字符串s按照字符串delim进行分割,然后返回分割的结果。
函数使用说:
1.strtok函数的实质上的处理是,strtok在s中查找包含在delim中的字符并用NULL(’\0′)来替换,直到找遍整个字符串。这句话有两层含义:(1)每次调用strtok函数只能获得一个分割单位。(2)要获得所有的分割单元必须反复调用strtok函数。
2.strtok函数以后的调用时的需用NULL来替换s.
3.形参s(要分割的字符串)对应的变量应用char s[]=”….”形式,而不能用char *s=”….”形式
#include <stdio.h>
#include <string.h>
void main()
{
char buf[]=”Golden Global View”;
char* token = strtok( buf, ” “);
while( token != NULL )
{
printf( ”%s “, token );
token = strtok( NULL, ” “);
}
return 0;
}
其结果为:
Golden
Global
View
其中第3条不知为何,我的理解是char *s 中的s保存的是字符串的首地址,它在内存中所分配的内存是连续的,但是超过字符串的长度后,其内存中的内容不可知;而char s[],它在内存中的分配也是连续的,但是超过字符串的长度后,其内存中的内容全部为'/0'。
例如
- #include <iostream>
- using namespace std;
- int main()
- {
- char *temp = "hewei";
- char Parms[6] = "hewei";
- int len = strlen(temp);
- int Temp_len = strlen(Parms);
- for(int i = 0; i< strlen(temp); i++)
- {
- cout << temp[i] << " " << Parms[i] << endl;
- }
- return 0;
- }
- 其调试结果:
- + temp 0x00417800 "hewei" char *
- Parms[8] -52 char
- + &Parms[0] 0x0012ff4c "hewei" char *
- + &Parms[1] 0x0012ff4d "ewei" char *
- + &Parms[2] 0x0012ff4e "wei" char *
- + &Parms[3] 0x0012ff4f "ei" char *
- + &Parms[4] 0x0012ff50 "i" char *
- + &Parms[5] 0x0012ff51 "" char *
- + &Parms[6] 0x0012ff52 "烫烫烫烫烫" char *
- + &temp[3] 0x00417803 "ei" char *
- + &temp[4] 0x00417804 "i" char *
- + &temp[5] 0x00417805 "" char *
- + &temp[6] 0x00417806 "" char *
- + &temp[7] 0x00417807 "" char *
- + &temp[8] 0x00417808 "" char *
- temp[6] 0 char
- temp[7] 0 char
- + temp 0x00417800 "hewei" char *