开发者

Remove new line character in C

I am trying to use getc(character) to take an element from a file and do stuff with it, but it appears that it must have a '\n' before the end of a line is met.

How can I remove this so that when I copy the 开发者_运维问答characters I don't have a new line character appearing anywhere - thus allowing me to deal with printing new lines when I choose?


.
.
.
#include <string.h>
.
. /* insert stuff here */
.
char* mystring = "THIS IS MY STRING\n"
char* deststring;
.
.
.
strncpy(deststring, mystring, strlen(mystring)-1);
.
.
.

(As an added note, I'm not a huge fan of dropping \0 characters in strings like that. It doesn't work well when you start doing i18n and the character width is not fixed. UTF-8, for example, can use anywhere from 1 to 4 bytes per "character".)


To replace all new line char with spaces, use:

char *pch = strstr(myStr, "\n");
while(pch != NULL)
{
    strncpy(pch, " ", 1);
    pch = strstr(myStr, "\n");
}

To remove first occurrence of new line char in string, use:

char *pch = strstr(myStr, "\n");
if(pch != NULL)
  strncpy(pch, "\0", 1);


Hmm, wouldn't help to use getc to fill a buffer and remove newline and carriage return characters?


You could replace it with a null terminator.

Here is one (simple) way to do it off the top of my head:

 mystr[ strlen(mystr) - 1 ] = '\0';


Supposing that buf is of type char and it holds the string value read in from the file...

buf[strlen(buf)-1] = '\0';

That sets the second-last character of the buffer to nul i.e. '\0' in order to remove the new-line character.

Edit: Since loz mentioned a compiler error I suspect it's a const char * is used...Can we see the code please...


The following will do the trick

line[strlen(line) - 1] = 0


A bit more complete version:

char* end = line + strlen(line) - 1 ;          // end of line                                                                                                      
while( (end > line) && isspace(*end) ) end--;  // right trim space                                                                                              
*(end+1) = '\0';                               // terminate string

(Note: Putting a null char into it makes string readers stop reading at that point but the memory footprint of line is the same. The characters to the right of the '\0' are still there.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜