[英]Reversing a string word by word wtih C language
我的代碼下面有問題,我試圖反轉一個字符串,但我有運行時錯誤,有人可以幫我查一下嗎? 問題是:
例如:
INPUT:char * s =“這是我的字符串”
輸出:“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();
}
您無法修改此字符串:
char *s = "This is my string";
你已經宣布它不正確,它應該是
const char* = "This is my string";
通常,這些字符串分配在您無法寫入的內存區域中。 您應該創建另一個緩沖區來將反向字符串寫入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.