Possible Duplicate:
Remove characters from a string in C
Do you have an example of C code to remove carriage returns in a string?
Possible Duplicate:
Remove characters from a string in C
Do you have an example of C code to remove carriage returns in a string?
The simplest solution is to probably just process the string character by character, with pointers for source and destination:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[] = "This is a two-line\r\nstring with DOS line endings.\r\n";
printf("%d [%s]\n",strlen(str), str);
// ========================
// Relevant code in this section.
char *src, *dst;
for (src = dst = str; *src != '\0'; src++) {
*dst = *src;
if (*dst != '\r') dst++;
}
*dst = '\0';
// ========================
printf("%d [%s]\n",strlen(str), str);
}
This sets up two pointers initially the same. It then copies a character and always advances the source pointer. However, it only advances the destination pointer if the character wasn't a carriage return. That way, all carriage returns are overwritten by either the next character or the null terminator. The output is:
51 [This is a two-line
string with DOS line endings.
]
49 [This is a two-line
string with DOS line endings.
]
This would be adequate for most strings. If your strings are truly massive in size (or this is something you need to do many times each second), you could look at a strchr
-based solution since the library function will most likely be optimised.
A generalized character removal function:
char *final=ptr;
while(*ptr != '\0')
{
if(*ptr == '\n') // Replace \n by your favorite character
{
temp=ptr;
while(*temp != '\0')
{
*temp = *(temp+1);
temp++;
}
}
ptr++;
}
A carriage return or any other char is easy to replace in a string and even easier to replace. Your question does not really shows what you're looking for so I've included sample code for both removing and replacing a char in a string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void remove_char_from_string(char c, char *str)
{
int i=0;
int len = strlen(str)+1;
for(i=0; i<len; i++)
{
if(str[i] == c)
{
// Move all the char following the char "c" by one to the left.
strncpy(&str[i],&str[i+1],len-i);
}
}
}
void replace_char_from_string(char from, char to, char *str)
{
int i = 0;
int len = strlen(str)+1;
for(i=0; i<len; i++)
{
if(str[i] == from)
{
str[i] = to;
}
}
}
int main(void) {
char *original = "a\nmultiline\nstring";
int original_len = strlen(original)+1;
char *string = (char *)malloc(original_len);
memset(string,0,original_len);
strncpy(string,original,original_len);
replace_char_from_string('\n',' ',string);
printf("String: %s\n",string); // print: String: a multiline string
remove_char_from_string(' ',string);
printf("String: %s\n",string); // print: String: amultilinestring
return 0;
}