I want to remove a character from an optional point of string in c lang.. I want to write this program via pointers and strcat() function. Please guid me
Thanks all
Here is a small example program I wrote for removing a character from a string using strcat
. I explained the steps in the comments.
You may have to add some extra features such as checking whether pos >= 0 && pos < strlen(string)
.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *removeCharacter(char *string, int pos);
int main(void) {
char string[] = "Testing strings"; // The string to remove chars from
char *newString; // The resulting string
newString = removeCharacter(string, 3);
printf("Result is '%s'\n", newString); // Print result
free(newString); // Clean up allocated memory for the resulting string.
return 0;
}
char *removeCharacter(char *string, int pos) {
char buffer[255]; // Temporary storage for the beginning of the string
char *appendix = string + (pos + 1); // Appendix (rest of the string without omitted character)
char *newString = (char *)malloc(255 * (sizeof(char))); // Allocate some memory for the resulting string
printf("Copying %d chars from %s to buffer...\n", pos, string);
strncpy(buffer, string, pos); // Copy pos characters from string to buffer (our beginning of the string)
buffer[pos] = '\0'; // Don't forget to add a NULL byte to indicate the end of the string
printf("Buffer is '%s' and appendix is '%s'\n", buffer, appendix);
strcat(newString, buffer); // Concatenate buffer (beginning) and appendix (ending without character)
strcat(newString, appendix);
return newString;
}
Why would you use
strcat()
for that? All you need ismemmove()
:Demo: http://codepad.org/SrgzQohD