[問題] 去除字串中空白字元的函式

看板C_and_CPP (C/C++)作者 (Respect disgrace)時間16年前 (2009/05/20 12:19), 編輯推噓6(603)
留言9則, 5人參與, 最新討論串1/2 (看更多)
在撰寫去除字串中的空白函式時 遇到了一些問題 可以麻煩一下版友 只出我的程式碼那邊有問題呢? #include <stdio.h> #include <stdlib.h> char *DeleteEmpty(char *Str); int main() { char *str1="My dear friend"; char *str2; printf("str1為%s\n", str1); str2=DeleteEmpty(str1); printf("str2為%s\n", str2); system("pause"); return 0; } char *DeleteEmpty(char *Str) { int i=0,j=0; char *str3; for(i=0;;i++) { if(Str[i]=='\0') //判斷字串結尾 break; else { if(Str[i]==' ') //判斷空白字元 { j=j+1; //計算空白字元個數 } str3[i]==Str[i+j]; } } return str3; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.243.66

05/20 12:21, , 1F
你執行時的問題是什麼
05/20 12:21, 1F

05/20 12:21, , 2F
置底十誡三四五
05/20 12:21, 2F

05/20 12:22, , 3F
str3 是 local variable.............
05/20 12:22, 3F

05/20 12:51, , 4F
小弟怎麼覺得問題主要是十誡之四const char string說.
05/20 12:51, 4F

05/20 12:54, , 5F
啊我錯了, 我以為str3指在原來Str的位置Orz
05/20 12:54, 5F

05/21 08:30, , 6F
str3 的 index 要用另一個變數 不能跟著 i
05/21 08:30, 6F

05/21 08:34, , 7F
str3[i]==... 在 assign 不該用 ==
05/21 08:34, 7F

05/22 17:47, , 8F
str3並未指向一個有效的記憶體區塊
05/22 17:47, 8F

05/22 17:48, , 9F
看是用malloc還是一開始就改成宣告陣列
05/22 17:48, 9F
文章代碼(AID): #1A4uJbZp (C_and_CPP)
文章代碼(AID): #1A4uJbZp (C_and_CPP)