【问题标题】:How can i add space between two words如何在两个单词之间添加空格
【发布时间】:2019-06-05 06:43:15
【问题描述】:

我正在尝试反转句子,但我无法在两个单词之间添加空格。当我尝试时它崩溃了。 我将str中的句子分配给代码中的sent。

void reverse(char *str)
{
char sent[100];
int i=lenght(str);
int t=0;
while(i>=-1)
{
    if(str[i]==' ' || str[i]=='\0' || i==-1)
    {

        int k=i+1;
        while(str[k]!=' ' && str[k]!='\0')
        {
            sent[t]=str[k];
            k++;
            t++;

        }
    }   
    i--;    
}

// INPUT: THIS SENTENCE IS AN EXAMPLE
// VARIABLE SENT= EXAMPLEANISSENTENCETHIS

【问题讨论】:

  • 除了标题还有什么问题? IE。你想做的事情不起作用怎么办?会发生什么意外?什么没有发生?您可以显示带有输出和所需输出的示例输入吗?
  • 为了帮助我们重现您将要更详细描述的情况,请将您的代码 sn-p 升级为minimal reproducible example
  • 我怀疑显示的代码甚至是您在家中实际代码的一部分,因为我怀疑这个 lenght 编译...
  • 抱歉,我的英语不太好,无法解释自己
  • 您从 i 作为字符串的长度开始。然后你访问k==i+1。请检查您的代码是否有任何超出字符串的访问,可能超出sent 的大小。

标签: c++ char c-strings


【解决方案1】:

插入空间你只需要这个修改(假设一切正常):

void reverse(char *str)
{
char sent[100];
int i=lenght(str);
int t=0;
while(i>=-1)
{
    // if str[i]==0 is not needed since you already start from the last char
    // (if it would have start from from the null char which end the string,
    // your app will crash when you try to access out of boundary array str[k] (where k is i+1)

    if(str[i]==' ' || i==-1)
    {

        int k=i+1;
        while(str[k]!=' ' && str[k]!='\0')
        {
            sent[t]=str[k];
            k++;
            t++;

        }
        // after having the reversed word lets add the space,
        // but let's not add it if we are in the end of the sentence:
        if(str[i] == ' ')
        {
            sent[t] = ' ';
            t++;
        }
    }   
    i--;    
}

// INPUT: THIS SENTENCE IS AN EXAMPLE
// VARIABLE SENT= EXAMPLEANISSENTENCETHIS

【讨论】: