Hi im attempting to remove a char from a C string, but the output doesnt seem correct. If for example. Input string = "Hello" Specified char to be removed = "l" My output is "HeXXo". I seem to need to push the values in after removing the char?
Code below:
#include <stdio.h>
#include <stdlib.h>
void squeeze(char str[], char c);
void main (){
char input[100];
char c;
printf("Enter string \n");
gets(input);
printf("Enter char \n");
scanf("%c", &c);
printf("char is %c \n", c);
squeeze(input , c );
getchar();
getchar();
getchar();
}
void squeeze(char str[], char c){
int count = 0, i = 0;
while (str[count] != '\0'){
count++;
}
printf("Count = %d \n", count);
for ( i = 0 ; i != count; i++){
if (str[i] == c){
printf("Found at str[%d] \n", i);
str[i] = "";
}
}
printf(" String is = %s", str);
}
Input: s = "daabcbaabcbc", part = "abc" Output: "dab" Explanation: The following operations are done: - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". - s = "dababc", remove "abc" starting at index 3, so s = "dab".
You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.
Using String. replace() method to remove all occurrences of each character from the string within a loop.
There is no method to replace or remove last character from string, but we can do it using string substring method.
str[i] = "";
You are trying to assign a pointer instead of a character. You probably meant ' '
but that's not the right way to delete characters from a string either, that's replacing them. Try:
char *p = str;
for (i = 0 ; i != count; i++) {
if (str[i] != c)
*p++ = str[i];
}
*p = 0;
Here is a solution that I like more:
char *p = s; /* p points to the most current "accepted" char. */
while (*s) {
/* If we accept a char we store it and we advance p. */
if (*s != ch)
*p++ = *s;
/* We always advance s. */
s++;
}
/* We 0-terminate p. */
*p = 0;
#include <stdio.h>
#include <stdlib.h>
void squeeze(char str[], char c);
int main ()
{
char input[100];
char c;
printf("Enter string \n");
gets(input);
printf("Enter char \n");
scanf("%c", &c);
printf("char is %c \n", c);
squeeze(input , c );
return 0;
}
void squeeze(char str[], char c){
int count = 0, i = 0,j=0;
char str2[100];
while (str[count] != '\0'){
count++;}
printf("Count = %d \n", count);
for ( i = 0,j=0 ; i != count; i++){
if (str[i] == c)
{
printf("Found at str[%d] \n", i);
// str[i] = '';
}
else
{
str2[j]=str[i];
j++ ;
}
}
str2[j]='\0' ;
printf(" String is = %s", str2);
}
This is the modified version of your code. I've created a new array and placed the rest of the non-matching letters into it. Hope it helps .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With