简体   繁体   中英

Reversing a string word by word wtih C language

I have a problem with my code below, I am trying to reverse a string, but I have run time error, anyone who can help me check it? The problem is:
eg:

INPUT: char *s = "This is my string"

OUTPUT: "string my is This"

#include <iostream>   
using namespace std;

void reverse(char *str, int start, int end){
    char tmp; 
    while(end > start){
        tmp = str[end];
        str[end] = str[start];
        str[start] = tmp;
        end--;
        start++;
    }
}

int main()
{
   char *s = "This is my string";
   int len = strlen(s);
   int start = 0;
   int end = len-1;
   reverse(s, start, end);   
   printf("%s", s); 
   end = 0;
   while( end < len){
        if(s[end] == ' '||s[end] =='\0'){
            while(s[start]==' ')
                start++;
            reverse(s,start,end-1);
            start = end;
        }   
        end++;
   }
   printf("%s", s); 
   cin.get();
}

You cannot modify this string:

char *s = "This is my string";

You've declared it incorrectly, it should be

const char* = "This is my string";

Normally these strings are allocated in a region of memory which you cannot write to. You should create another buffer to write the reversed string to.

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