开发者

How to remove a carriage return from a string in C? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Remove characters from a string in C

Do you have an example of C code to remove carriage returns i开发者_C百科n 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 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜