字符串标记不使用的strtok() [英] String tokenizer without using strtok()

查看:145
本文介绍了字符串标记不使用的strtok()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个字符串标记不使用的strtok的过程中()。这主要是针对我自己的改善和指针更深入的了解。我想,我几乎有它,但我一直收到以下错误:

I'm in the process of writing a string tokenizer without using strtok(). This is mainly for my own betterment and for a greater understanding of pointers. I think I almost have it, but I've been receiving the following errors:

myToc.c:25 warning: assignment makes integer from pointer without a cast
myToc.c:35 (same as above)
myToc.c:44 error: invalid type argument of 'unary *' (have 'int')

我在做什么是通过发送到方法的字符串循环,发现每个分隔符,并用它替换'\\ 0'。的PTR数组是应该有指针的分离子。这是我到目前为止所。

What I'm doing is looping through the string sent to the method, finding each delimiter, and replacing it with '\0.' The "ptr" array is supposed to have pointers to the separated substrings. This is what I have so far.

#include <string.h>

void myToc(char * str){
   int spcCount = 0;
   int ptrIndex = 0;

   int n = strlen(str);

   for(int i = 0; i < n; i++){
      if(i != 0 && str[i] == ' ' && str[i-1] != ' '){
         spcCount++;
      }
   }

   //Pointer array; +1 for \0 character, +1 for one word more than number of spaces
   int *ptr = (int *) calloc(spcCount+2, sizeof(char));
   ptr[spcCount+1] = '\0';
   //Used to differentiate separating spaces from unnecessary ones
   char temp;

   for(int j = 0; j < n; j++){
      if(j == 0){
         /*Line 25*/ ptr[ptrIndex] = &str[j];
         temp = str[j];
         ptrIndex++;
      }
      else{
         if(str[j] == ' '){
            temp = str[j];
            str[j] = '\0';
         }
         else if(str[j] != ' ' && str[j] != '\0' && temp == ' '){
            /*Line 35*/ ptr[ptrIndex] = &str[j];
            temp = str[j];
            ptrIndex++;
         }
      }
   }

   int k = 0;
   while(ptr[k] != '\0'){
      /*Line 44*/ printf("%s \n", *ptr[k]);
      k++;
   }
}

我能看到的错误发生,但我不知道如何解决这些问题。我该怎么办?我是不是正确分配内存或者是它只是我如何指定地址?

I can see where the errors are occurring but I'm not sure how to correct them. What should I do? Am I allocating memory correctly or is it just an issue with how I'm specifying the addresses?

推荐答案

您指针数组是错误的。它看起来像你想要的:

You pointer array is wrong. It looks like you want:

char **ptr =  calloc(spcCount+2, sizeof(char*));

另外,如果我正确地读你的code,有没有必要,因为这阵空字节是不是一个字符串。

Also, if I am reading your code correctly, there is no need for the null byte as this array is not a string.

此外,你需要解决:

while(ptr[k] != '\0'){
  /*Line 44*/ printf("%s \n", *ptr[k]);
  k++;
}

则不需要解引用,如果你删除空PTR,这应该工作:

The dereference is not required and if you remove the null ptr, this should work:

for ( k = 0; k < ptrIndex; k++ ){
  /*Line 44*/ printf("%s \n", ptr[k]);
}

这篇关于字符串标记不使用的strtok()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆