如何在两个词之间添加空格

时间:2019-06-05 06:43:15

标签: c++ char c-strings

我正试图颠倒句子,但是我不能在两个词之间添加空格。我尝试时会崩溃。 我将str中的句子分配给代码中发送的内容。

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

1 个答案:

答案 0 :(得分:0)

要插入空间,您只需要进行此修改(假设其他所有功能都正常):

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