我試圖從用戶那里獲取一個字串,然后洗掉字串中的所有字符,字母除外。string 包含空格的字串。我輸入了一個字串,但輸出只有“@@”。
我不知道發生了什么。
//C program
//Program to remove all characters in a string, except alphabet
#include <stdio.h>
#include <string.h>
int main()
{
char str[150], copy[150];
int i = 0, j = 0;
printf("\nEnter a string : ");
fgets(str,150,stdin);
for (i = 0; i < 150; i )
{
if ((str[i] >= 'a' && str[i] <= 'z') ||
(str[i] >= 'A' && str[i] <= 'Z') || (str[i] == '\0') )
{
*(copy j) == *(str i);
j ;
}
}
printf("\nResultant String : ");
for (int i = 0; i < strlen(str); i )
{
printf("%c",copy[i]);
}
printf("\n");
return 0;
}
在終端上,這是正在運行的程式,我輸入“1 2 3 4 get on the dance floor”。
Enter a string : 1 2 3 4 get on the dance floor
Resultant String : @@
uj5u.com熱心網友回復:
主要問題是你沒有在這里做作業:
*(copy j) == *(str i);
是==為了比較。你想要=:
*(copy j) = *(str i);
您的回圈條件也不正確:
for (i = 0; i < 150; i )
...
for (int i = 0; i < strlen(str); i )
對于第一個回圈,您正在讀取源陣列中的所有位元組,而不僅僅是設定的位元組,而在第二個回圈中,您使用源字串的長度而不是結果字串來列印結果。這些應該是:
for (i = 0; i < strlen(str); i )
...
for (int i = 0; i < strlen(copy); i )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433676.html
上一篇:Python字串替換不按預期作業
