c - 没有库函数将单词从句子中分离出来

标签 c arrays dynamic-memory-allocation

我在这里写了一段代码,不使用 strtok() 函数将给定句子中的单词分开。但问题是它只打印第一个单词。为什么其余单词不打印?

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="This, a sample string.";
  int i=0,k,begin,end;
  while(str[i]!='\0'){
    while(str[i]==' '){
        i++;
    }
    begin = i;
    while(str[i]!=' ' && str[i]!='\0'){
        i++;
    }
    end  = i-1;
    char *ptr =(char *)malloc((end-begin)*sizeof(char));
    for(k=begin;k<=end;k++){
        ptr[k] = str[k];
    }

    printf("%s\n",ptr);
    if(str[i]=='\0'){
        break;
    }
  }
}

最佳答案

完整的代码应该是这样的

我已经在您的代码之上更改了代码。

int main ()
{
        char str[] ="This, a sample string.";
        int i=0,k,begin,end;

        int t;

        while(str[i]!='\0'){
                begin = i;
                while(str[i]!=' ' && str[i]!='\0'){
                        i++;
                }
                end  = i-1;

                char *ptr = (char *) malloc( (i-begin)*sizeof(char) + 1);

                t=0;
                for(k=begin;k<=end;k++){
                        ptr[t++] = str[k];
                }
                ptr[t] = '\0';

                puts(ptr);

                if(str[i]=='\0'){
                        break;
                } else
                        while(str[i] == ' ') i++;  //To avoid multiple spaces
        }

        return 0;
}

-谢谢

关于c - 没有库函数将单词从句子中分离出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40147794/

相关文章:

c - 打印长的十六进制字符串

java - 用 2D 数组表示 8x8 维度的问题

c - a1,a2...a10 等于每个元素并对元素进行计数

c++ - 将结构的动态数组传递给 GPU 内核

C - 某处段错误

字符串化变量的 C 宏

c - 堆变量是全局变量,什么是堆变量的范围和生命周期

c - 释放后重新分配给指针变量

android - 如何在 Android SDL2.0 NDK C 上获取屏幕尺寸?

c++ - 将具有二维数组输入的函数传递给函数