简体   繁体   中英

String reverse without to turn the numbers in c

int  main()
{
 char str[1000],temp;
 int i,j=0;

 printf("String: ");
 gets(str);

 i=0;
 j=strlen(str)-1;

 while(i<j)
{
    temp=str[i];
    str[i]=str[j];
    str[j]=temp;
    i++;
    j--;
}
 printf("\n");
 printf("%s",str);
 return 0;
}

I want to change the rota

- In: 15 15 15 15 15 0 0
- Out: 0 0 51 51 51 51 51 but i want : 0 0 15 15 15 15 15

It's because you basically mirror the string without caring about the contents of the string. You need the code to be aware that the string contains space-delimited sub-strings, and reverse based on that.

One way is to tokenize the string (with eg strtok ) and push the sub-string onto a stack, and then recreate the string from the stack.

You are now reversing the order of the characters in the string, but it seems that you want to reverse the order of the space-separated fields instead. To achieve this, one way would be to iterate through the array backwards and print the tail every time you encounter a space, then replace the space with a '\\0' . Or form an array of strings with the space-separated fields as elements, then reverse the order of that array (same method as now, but dealing with pointers to char instead of char s).

Call this function to reverse the string. It accepts the string, then pushes each word onto stack until the string is empty. Then it starts popping out the words from stack thereby reversing the string, but not the words.

void rev(char *str){
    char s[20];
    int i=0;
    for(; str[i]!=' ' && str[i]!='\0'; i++)
        s[i]=str[i];
    s[i]='\0';
    if(str[i]==' ')
        rev(str+i+1);
    printf("%s ",s);
}

Steps to do:

  1. Write a string reverse function. Say reverseString(char* str)
  2. Pass the whole string to this function. you will get

    0 0 51 51 51 51 51

  3. Get each element by splitting for spaces in an array. Say...

    arr[0] = 0; arr[1] = 0; arr[2] = 51; arr[3] = 51; ...

  4. Pass individual array to string reverse function.Example:

    reverseString(arr[0]); reverseString(arr[1]); reverseString(arr[2]); ...

    5 Concatenate the array and you will get

    0 0 15 15 15 15 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM