【问题标题】:Split a string between words and insert newlines在单词之间拆分字符串并插入换行符
【发布时间】:2015-01-14 09:01:53
【问题描述】:

我有一个由几句话组成的字符串。 例如:

 hello world bye bye

现在,我需要把这句话变成一个单词:

hello
world
bye
bye

我有这个想法,但我不知道如何正确编写它,所以我希望你们能帮助我。 这是我目前所拥有的:

int len=0, k=0, stopatspace=0;
char temptext[100][15]={0};
char line[300]={0};

   len=strlen(line);
   printf("len is: %d", len);
   for(k=0; k<len; k++)
   {
       if (k == ' ')
       {
           // i dont know what to write here in order to make it a cloumn 
       }
   }

基本上,我的想法是在我的行的所有长度上运行,当我到达一个空间时,我希望它进入(向下走一行,这样它看起来像一个库)

【问题讨论】:

  • 当您说“让它成为一列单词”时,您是要存储数据还是只想打印文本作为列? (我知道你有这个变量temptext,但你好像没用过,你的问题也不是很清楚。)
  • lili,如果您有“我不能使用指针”之类的要求,请在您的问题中提及。
  • 简而言之,除非明确指定标记的数量及其长度,否则在没有任何指针的情况下在 C 中实现您的想法是不可能的。

标签: c arrays string split


【解决方案1】:

假设line 是包含hello world bye byechar 数组,text 被声明为

char text[100][15]; //I used 100 and 15 because your example contains it

并且您希望将每个单词复制到text 的每一行中。然后,使用strtok() 函数和" "(space) 作为分隔符,并将其放在一个循环中,当strtok() 返回NULL 以获取每个单词时终止。在循环中使用strcpy() 将每个单词复制到text 的每一行。

此代码将如下所示:

char text[100][15];
char line[]="hello world bye bye";
int i=0;

char *token=strtok(line," ");

while(token!=NULL)
{
  strcpy(text[i],token);
  i++;
  token=strtok(NULL," ");
}

现在,要打印它,你可以使用

for(int j=0;j<i;j++)
  printf("text[%d]=%s",j,text[j]);


另一种方法是手动复制每个字符,直到看到空格。
int len=strlen(line);
int i=0;
int k=0;

for(int j=0;j<len+1;j++)
{
  if(line[j]==' ')
  {
    text[i][k]='\0';
    i++;
    k=0;
  }
  else
  {
    text[i][k]=line[j];
    k++;
  }
}

请注意,上面的代码不会阻止buffer overflows。您可以使用

打印每个单词
for(int j=0;j<i+1;j++)
  printf("text[%d]=%s",j,text[j]);

【讨论】:

  • 我展示了同样的东西,OP说不应该使用指针:(
【解决方案2】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
        char string[100];
        fgets(string, 100, stdin);
        string[strlen(string)-1] = 0;

        // create an array of pointers
        char **string_array = (char**)malloc(sizeof(char*));

        int i = 0, array_size;

        // tokenize input
        char *token = strtok(string, " ");
        while(token!=NULL) {
                // dynamically increase the array during run time
                string_array = (char**)realloc(string_array, (i+1)*sizeof(char**));
                // create the string as you would do when there is only one string
                string_array[i] = (char*)malloc(strlen(token)+1);
                strcpy(string_array[i], token);
                token = strtok(NULL, " ");
                i++;
        }
        array_size = i;

        for(i=0; i<array_size; i++) {
               printf("%s\n", string_array[i]);
        }

        return 0;
}

基本上,您创建一个指针数组并为字符串一一分配内存,就像只有一个字符串时所做的那样。 (如果不知道token的个数,使用realloc来增加指针的大小。)

【讨论】:

  • @Gopi ,OP 从未在他的帖子中提到这一点,因此大多数人不会注意到它,因为 OP 仅将其作为我的答案(以及您已删除的答案)下的评论告诉它。
  • @Gopi ,事实上,OP 在他的问题中提到:“我的想法是在我的线路的所有长度上运行,当我到达一个空间时,我希望它进入”和问题的标题是“将字符串转换为二维数组”。然而,如果不使用指针,就没有办法做到这一点,因为在用户输入之前令牌的数量和它们的长度是未知的。因此必须动态创建数组。
【解决方案3】:
#include <stdio.h>
#include <ctype.h>

int main(void){
    char line[300] = "hello world bye bye\n";
    char temptext[100][15]={0};
    int i=0, j, k=0;

    while(line[k]){
        if(isspace(line[k])){
            ++k;//skip space to word
            continue;
        }
        for(j=0; j < 15-1 && line[k] && !isspace(line[k]); ++k, ++j)
            temptext[i][j] = line[k];
        if(j && ++i == 100)
            break;
    }
    for(j=0; j<i; ++j)
        puts(temptext[j]);
    return 0;
}

【讨论】:

    【解决方案4】:
    #include<stdio.h>
    #define NEWLINE printf("\n")
    int main(void)
    {
            char string[]="hello world bye bye";
            int index=0;
            while(string[index])
            {
                    if(string[index]==32)
                    {
                            NEWLINE;
                            index++;
                    }
                    else
                    {
                            printf("%c",string[index]);
                            index++;
                    }
            }
            NEWLINE;
    }
    
    // Whenever i encountered with a space, i am printing a new line on the screen. Here 32       is the ASCII value for space
    

    【讨论】:

    • 我喜欢这个简单的解决方案,因为这很可能是 OP 想要的。但是为什么丑陋的宏 NEWLINE 什么都买不到呢?为什么硬编码数字 32 而不是 ' '?为什么不将增量移出条件块,使其只发生一次?请从main 返回一个值。 (顺便说一句,这不是我的反对意见。)
    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多