我的代码下面有问题,我正在尝试反转字符串,但我有运行时错误,有人可以帮我查一下吗?问题是:
例如:
INPUT:char * s =“这是我的字符串”
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();
}
答案 0 :(得分:3)
您无法修改此字符串:
char *s = "This is my string";
你已经宣布错误,它应该是
const char* = "This is my string";
通常,这些字符串分配在您无法写入的内存区域中。您应该创建另一个缓冲区来将反转的字符串写入。