Sunday, August 2, 2009

Problem on C program(strings)...please try to solve.?

write a C function void str_copy_drop(const char * string1, char * string2, char ch)


which copies the string string1 to string2 but with all occurrences of the character


passed as parameter ch omitted.








HERE IS WHAT I HAVE TRIED: its funny but can you check it and write me a correct program..





#include%26lt;stdio.h%26gt;


#include%26lt;string.h%26gt;


void str_copy_drop(const char *string1, char *string2, char ch);








void str_copy_drop(const char *string1, char *string2, char ch)


{


char *s1[20],*s2[20];








FILE *input;


input =fopen("string.txt","r");





fscanf(input,"%s",%26amp;s1);





s2= strcpy(s2,s1);


printf("\ncopied string is %s\n",s2);


}








above programs is wrong...i need solution for question described above..





Many thanks!!

Problem on C program(strings)...please try to solve.?
Use this function instead of yours. It would work fine.





void copy(char *s1,char *s2,char ch)


{


while(*s1!='\0')


{


if(*s1!=ch)


{


*s2=*s1;


s2++;


}


s1++;


}


*s2='\0';


}








U can ask more such..








OM NAMAH SHIVAY
Reply:/*


copy all characters from string1 into string2 except ch





method:


walks through each character in string1 using a pointer to


the characters, stopping at the C end-of-string char '\0', and


steps the pointer by the sizeof(char)





appends an end-of-string char to the output string2 after all valid characters have been copied.





NOTE BENE: output buffer (string2) must be sufficient to hold all characters of input buffer (string1). No checking is done to ensure this here.


*/


void str_copy_drop(const char *string1, char *string2, char ch) {





if (( 0 != string1 ) %26amp;%26amp; ( 0 != string2)) {


char* p1 = (char*)string1;


char* p2 = string2;





while ( (*p1) != '\0' ) {


if ( (*p1) != ch ) {


(*p2) = (*p1);


p2 += sizeof(char);


}


p1 += sizeof(char);


}


(*p2) = '\0';


}


}





You'll have to format the indentation yourself, as yA doesn't allow tabs.
Reply:you would have to go through the string, character by character and compare it with the parameter ch. if it matches then dont copy it to the new string. you need to know the length of the string so you know how many characters to compare.





pseudocode:


set 2 counters to 0


get length of string


loop "length of string" times


if string1[couter1] = !ch


copy string1[counter1] to string2[counter2]


increment counter2


loop until at end of string1





just a note (going by your function declaration), the file should be opened outside of the routine and read. then pass the pointer to the string. you dont need the "char s1, s2 pointers since you are passing the string pointers to the function (which you are not using by the way).


No comments:

Post a Comment