C++分割字符串函数

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'。 

例如 
C++代码   收藏代码
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     char *temp = "hewei";  
  7.     char Parms[6] = "hewei";  
  8.     int len = strlen(temp);  
  9.     int Temp_len = strlen(Parms);  
  10.     for(int i = 0; i< strlen(temp); i++)  
  11.     {  
  12.           cout << temp[i] << " " << Parms[i] << endl;  
  13.     }  
  14.     return 0;  
  15. }  
  16.   
  17. 其调试结果:  
  18. +       temp    0x00417800 "hewei"  char *  
  19.         Parms[8]    -52 char  
  20. +       &Parms[0]   0x0012ff4c "hewei"  char *  
  21. +       &Parms[1]   0x0012ff4d "ewei"   char *  
  22. +       &Parms[2]   0x0012ff4e "wei"    char *  
  23. +       &Parms[3]   0x0012ff4f "ei" char *  
  24. +       &Parms[4]   0x0012ff50 "i"  char *  
  25. +       &Parms[5]   0x0012ff51 ""   char *  
  26. +       &Parms[6]   0x0012ff52 "烫烫烫烫烫"  char *  
  27. +       &temp[3]    0x00417803 "ei" char *  
  28. +       &temp[4]    0x00417804 "i"  char *  
  29. +       &temp[5]    0x00417805 ""   char *  
  30. +       &temp[6]    0x00417806 ""   char *  
  31. +       &temp[7]    0x00417807 ""   char *  
  32. +       &temp[8]    0x00417808 ""   char *  
  33.         temp[6] 0   char  
  34.         temp[7] 0   char  
  35. +       temp    0x00417800 "hewei"  char *  
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值