Reverse the ordering of words in a string

后端 未结 30 3815
青春惊慌失措
青春惊慌失措 2020-11-22 10:23

I have this string s1 = \"My name is X Y Z\" and I want to reverse the order of the words so that s1 = \"Z Y X is name My\".

I can do it u

30条回答
  •  醉酒成梦
    2020-11-22 11:05

    This is assuming all words are separated by spaces:

    #include 
    #include 
    
    int main()
    {
        char string[] = "What are you looking at";
        int i, n = strlen(string);
    
        int tail = n-1;
        for(i=n-1;i>=0;i--)
        {
            if(string[i] == ' ' || i == 0)
            {
                int cursor = (i==0? i: i+1);
                while(cursor <= tail)
                    printf("%c", string[cursor++]);
                printf(" ");
                tail = i-1;
            }
        }
        return 0;
    }
    

提交回复
热议问题