字符串三角形,空格作为分隔符C语言

问题描述 投票:-4回答:2

这是一个独特的三角形,并且以这种方式不同于所有其他三角形,它打印由空格分隔的单词。我正在寻找的答案在我已经检查过的任何其他问题中都没有。

输出应该是这样的

这个 这是 这是 这是最好的 这是最好的方法 这是最好的方法 这是最好的消费方式 这是花时间的最佳方式

到目前为止我的代码是

#include <stdio.h>

int main()
{

    char msg[]="this is the best way to spend time for reedaf";
    int inn=1, out, i=0, max;
    max=(sizeof(msg)/sizeof(int))+1;
    char *output;
    char *spc=" ";
      output=strtok(msg,spc);
    for(out=1;out<max;out++){

        for(i=0;i<out && output != NULL ;i++){

      printf("%s ", output);
      output=strtok(NULL,spc);

          }

    printf("\n");

    }
    return 0;
}

这会生成此输出

这个 是个 最好的方式 花时间做reedaf

所以请帮助我,我找不到安心

我需要用数组中的起始单词开始每一行。那么下一行应该从数组中的起始单词开始,然后是下一个单词。然后下一行应该再次从数组中的起始单词开始,然后是下一个单词,然后是下一个单词。依此类推。

请不要试图休息;或memcpy

c string space delimiter
2个回答
2
投票

OP使用strtok()不会根据需要恢复字符串,而只是简化字符串。

以下是候选简化。

void printTri(char *s) {
  for (size_t i = 0; s[i]; i++) {
    if (s[i] == ' ') {
      s[i] = '\0';
      puts(s);
      s[i] = ' ';
    }
  }
  puts(s);
}

int main(void) {
  char msg[] = "this is the best way to spend time for reedaf";
  printTri(msg);
  return 0;
}

1
投票

我不完全确定您在代码中所做的事情,但您要求的输出可以通过此代码获得。

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

int main()
{
char str[]="this is the best way to spend time for reedaf",ch=' ',c='$';
int n=0,x,i,j;
x=strlen(str);
for(i=0;i<x;i++)
{
    if(str[i]==ch)
        n++;
}
for(i=0;i<n+1;i++)
{
    for(j=0;j<x;j++)
    {
        if(str[j]==ch)
        {
            str[j]=c;
            break;
        }
        else
        {
            if(str[j]==c)
                printf("%c",ch);
            else
                printf("%c",str[j]);
        }
    }
    printf("\n");
}
return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.