Does anyone know how to remove unwanted char e.g. '\n' from strings. As in perl we have a function called chomp($str) which only removes '\n' from the string if it exist.
What is the best way to remove newline char '\n' from string.
As this is the C forum and the likely hood of the availablity of the MFC class CString, and the fact that the chomp() function in Perl removes only the end of the record marker (usually, "\n" I'm assuming your looking to remove the last character and not all occurances of "\n". To do this in C do something like this:
mystring[strlen(mystring)-1] = '\0';
That will cut off the last character of the string regardless.
for(i=0;str!='\0';i++)
{
if(str=='\n')
{
str=' ';
}
}
Hope this solves the problem u r asking for.
It is very simple in C nothing to remember just plain vanilla logic. s-)
Regards,
SwapSawe.
Im sorry once again... that is twice in my jumping around from forums that I forgot where I was. Please forgive my absent minded posts, by the end of the day at work I tend to be more asleep at the wheel |-I
If you truly want to remove the newline (not replace it with a space) here are a few different ways to do it. Each of the functions below is made more generic by allowing you to remove a specified character and letting the user know how many characters were removed.
This one changes the string in place. Generally this is the way *not* to do it due to inefficiency (calling memmove() for each occurance of c) and its only advantage is that you don't have to use another variable.
*removed=0;
if (dest!=NULL) {
while (*src) {
if (*src!=c) {
*dest++=*src;
} else {
++(*removed);
}
++src;
}
*dest=0;
}
return start;
}
This is an improvement. The function dynamically allocates a buffer large enough to hold the entire source string and then only copies in the characters that do not match c. The disadvantage is that the user must call free() on the pointer returned eventually. Since the function returns the result string, the # of characters removed is stuffed in a pointer provided by the user.
int
remove_char3(const char *src,char *dest,char c)
{
int removed=0;
while (*src) {
if (*src!=c) {
*dest++=*src;
} else {
++removed;
}
++src;
}
*dest=0;
return removed;
}
This one stores the result in a user-supplied pointer that is assumed to point to enough memory to hold the result string and is similar to how the standard library functions behave.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.