Reverse the ordering of words in a string

后端 未结 30 4379
青春惊慌失措
青春惊慌失措 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:18

    In c, this is how you might do it, O(N) and only using O(1) data structures (i.e. a char).

    #include
    #include
    main(){
      char* a = malloc(1000);
      fscanf(stdin, "%[^\0\n]", a);
      int x = 0, y;
      while(a[x]!='\0')
      {
        if (a[x]==' ' || a[x]=='\n')
        {
          x++;
        }
        else
        {
          y=x;
          while(a[y]!='\0' && a[y]!=' ' && a[y]!='\n')
          { 
            y++;
          }
          int z=y;
          while(x

提交回复
热议问题