Click here to Skip to main content
14,739,187 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone! I need your help if you can.I have to run a programm who removes a specific character from a given string.I have a function who has a string and a char.For example the word hello is the string and the character is l.My new string I want to be heo.I have written my code but my output is null.Can you help me to find my mistake??
Here is my code:
char* Delete(char *s1,char c)
    char *s2; //the new string
    int n1,n2=0,n3;
    n1=strlen(s1); //find the length of my string
    while(*s1!='\0') //in this loop i find how many characters is similar to c 
    n3=n1-n2; //find the length of new string s2
    s2=(char *)malloc((n3+1)*sizeof(char));
   return s2;

int main()
   char s1[20],c;
   printf("The new string is: %s",Delete(s1,c));

    return 0;

What I have tried:

Help me please i am a beginner so i need your advice!
Updated 11-Aug-20 2:02am

The first thing to reach for when your code doesn't work is a debugger: it would have shown you the problem in seconds!

How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.
Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Hint: where is s1 pointing after the first loop is finished?
Your first loop in the Delete function iterates s1 until it finds the null terminator. So s1 now points at the end of the string. So when you run the second loop s1 appears to contain nothing. A much simpler method is to allocate a buffer which is the same length as s1 and just perform the second loop where you skip the matching letters. However that still produces null since s2 will point at the null terminator at the end of the loop. So you need another pointer, which is a copy of s2. At the end of the loop return this pointer which will still point to the beginning of the new string.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900