所以這裏的練習是設計一個程序,它接受一個字符串並刪除出現在第二個字符串中的字符串中的所有字符。所以對於我在下面選擇的字符串,其中第一個字符串是abc,第二個字符串是cde,我希望得到ab
的輸出,而不是abc
。K&R練習擠壓功能
我已經看到一個非常簡潔的方法來做這個擠壓功能,只需要兩個簡單的循環,但我想知道爲什麼我長長的蜿蜒的方式不起作用。
#include<stdio.h>
void squeeze(char s1[], char s2[]);
void copy(char to[], char from[]);
int k=0;
main()
{
char array1[4]="abc";
char array2[4]="cde";
squeeze(array1, array2);
printf("%s", array1);
}
void squeeze(char s1[], char s2[])
{
int j,i,m;
m=j=i=0;
char s3[1000];
while(s1[i]!='\0') //What I'm doing here is taking a character in the string
{ //and comparing it with all characters in the second string.
copy(s3,s1); //If it exists in the second string I'm 'deleting' that letter
while(s2[j]!='\0') //from the first string. Then I start all over again with the
{ // next letter in line. Or at least that's the plan.
if (s1[i]==s2[j])
{
k=1;
}
++j;
}
if (k==1)
{
m=i;
while(s3[m+1]!='\0')
{
s1[m]=s3[m+1]; //I'm 'deleting' the letter by pushing each character
++m; //that is to the right of the deleted character to the
} //left of the array.
}
if(k!=1)
{
++i;
}
}
s1[i]='\0';
}
void copy(char to[], char from[])
{
int i;
i=0;
while(from[i]!='\0')
{
to[i]= from[i];
++i;
}
to[i]=='\0';
}
+1爲'從不使用全局變量'的評論。它是一個輕微的過度陳述,但在這裏準確的'k'只在一個函數中使用。只有當需要從函數外部訪問時,才能在函數之外創建一個變量。 –
好的,謝謝!順便說一句,我不增加「我」,因爲如果我已經'刪除'的字符,所以下一個字符是在陣列中的當前位置'我'。不是嗎? – MethequalsMath