简体   繁体   English

如何在字符串中添加空字符?

[英]how to add null characters to strings?

So I'm trying to tokenize a string without strtok for a homework assignment. 因此,我正在尝试将没有strtok的字符串标记为作业。 The professor recommended that we add '\\0' where there is a whitespace to break the string into parts like strtok. 教授建议我们添加'\\ 0',其中有一个空格将字符串分成strtok等部分。 My problem is once I find the first whitespace, I can add a '\\0' character to it, but then it stops there and I can't add '\\0' to other white space characters after that. 我的问题是,一旦我找到第一个空格,我可以为它添加一个'\\ 0'字符,但它会停在那里,之后我不能将'\\ 0'添加到其他空白字符。

     int tokenize(char *line, int len){
        int i;
        char *ptr = line;
        for(i=0; i<len; i++){

           if(isspace(ptr[i]){
              ptr[i]='\0'; 

           }
        }

       return 1;
      }

     int main(){

       char *line= "wo rd ";

       int len = strlen(line);
       tokenize(line, len);

       return 1;
     }

Isspace function will search the string only till it encounters the NULL(\\0) character. Isspace函数将仅搜索字符串,直到遇到NULL(\\ 0)字符。 hence compare the string elements with the space (or ASCII value) to recognize the space and replace it with a '\\0' character. 因此将字符串元素与空格(或ASCII值)进行比较以识别空格并将其替换为'\\ 0'字符。

 int tokenize(char *line, int len){
        int i;
        char *ptr = line;
        for(i=0; i<len; i++){

           if(ptr[i] == ' '){
              ptr[i]='\0'; 

           }
        }

       return 1;
      }

     int main(){

       char *line= "wo rd ";

       int len = strlen(line);
       tokenize(line, len);

       return 1;
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM