473,668 Members | 2,318 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trimming whitespaces

have a bit of c code that is ment to take a string (that may or may not
have spaces before or after the string) i.e. " stuff ", and trims off
the whitespace before and after.
Code:

char *trim (char *str, char ch)
{
char *first, *last;
int count;

/* Move first to the first character that isn't the same as ch */
for (first = str; *first == ch; first++);
/* Move last to the null character. Thats the only way to know 100% we
are
* removing items from the end of the string */
for (last = first; *last != '\0'; last++);
/* Ok now we backtrack until we find a character that isn't the same as
ch */
for (last--; *last == ch; last--);

if ( first != str)
{
for (count=0; count< last - first + 1; count++)
str[count] = *(first+count);
str[count] = '\0';
}
else
{
str[last-first] = '\0';
}

return str;
}

the problem is that it always removes the last letter of str as well.
i.e.
" stuff " -> "stuf" any ideas why this is happening.
Cheers
John

Nov 15 '05 #1
13 3665
jo******@hotmai l.com wrote:

have a bit of c code that is ment to take a string
(that may or may not
have spaces before or after the string) i.e. " stuff ", and trims off
the whitespace before and after.
Code:

char *trim (char *str, char ch)
{
char *first, *last;
int count;

/* Move first to the first character that isn't the same as ch */
for (first = str; *first == ch; first++);
That line could over run an array when (ch == '\0').
/* Ok now we backtrack until we find a character that
isn't the same as ch */
for (last--; *last == ch; last--);


When a string consists of a null terminated array of
characters which are all equal to ch, then what happens?

--
pete
Nov 15 '05 #2
pete wrote:

jo******@hotmai l.com wrote:

have a bit of c code that is ment to take a string
(that may or may not
have spaces before or after the string)
i.e. " stuff ", and trims off
the whitespace before and after.
Code:

char *trim (char *str, char ch)
{
char *first, *last;
int count;

/* Move first to the first character that isn't the same as ch */
for (first = str; *first == ch; first++);


That line could over run an array when (ch == '\0').
/* Ok now we backtrack until we find a character that
isn't the same as ch */
for (last--; *last == ch; last--);


When a string consists of a null terminated array of
characters which are all equal to ch, then what happens?


#include <string.h>

char *trim(char *str, char ch)
{
char *const p = str;

while (*str != '\0' && *str == ch) {
++str;
}
memmove(p, str, 1 + strlen(str));
str = p + strlen(p);
while (str != p && *--str == ch) {
*str = '\0';
}
return p;
}

--
pete
Nov 15 '05 #3
John,
Are you passing const char* as an argument to the trim function?
i.e. let's say in main() are you invoking trim(" stuff ", ' ');
If you are passing const char* like this you can't do any changes in
str[] subscript because this is a read-only section which you can't
change.
If you have to pass an argument in trim , it has to be either an array
address or allocated pointer.

Nov 15 '05 #4
John,
This is a code which will work fine:-

char *trim (char *str, char ch)
{
char *first, *last;

for (first = str; *first == ch; first++);
str = first;
for (last = str; *last != ch; last++) ;
*last = '\0';
return str;
}

Nov 15 '05 #5


Rajan wrote:
John,
This is a code which will work fine:-

char *trim (char *str, char ch)
{
char *first, *last;

for (first = str; *first == ch; first++);
str = first;
for (last = str; *last != ch; last++) ;
*last = '\0';
return str;
}


It would not work if str is a empty string, i.e. "".
Also, it will fail if all the characters in str are value ch, i.e.
char buf[32] = "aaaaaaa";
trim(buf,'a');

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 15 '05 #6
On Thu, 23 Jun 2005 09:24:53 -0400, Al Bowers wrote:
Rajan wrote:
John,
This is a code which will work fine:-

char *trim (char *str, char ch)
{
char *first, *last;

for (first = str; *first == ch; first++);
str = first;
for (last = str; *last != ch; last++) ;
*last = '\0';
return str;
}


It would not work if str is a empty string, i.e. "".
Also, it will fail if all the characters in str are value ch, i.e.
char buf[32] = "aaaaaaa";
trim(buf,'a');


.... and it finds the first "ch" after first "non-ch" not the first of a
conscutive run of "ch" at the end of str as - the original code clearly
intended.

Because this function returns a pointer other than the one it was passed
if the storage is malloced it can't be freed with out holding onto the
original pointer somewhere else making it complicated to use in some
situations.

--
Ben.

Nov 15 '05 #7


Ben Bacarisse wrote:
On Thu, 23 Jun 2005 09:24:53 -0400, Al Bowers wrote:

Rajan wrote:
John,
This is a code which will work fine:-

char *trim (char *str, char ch)
{
char *first, *last;

for (first = str; *first == ch; first++);
str = first;
for (last = str; *last != ch; last++) ;
*last = '\0';
return str;
}


It would not work if str is a empty string, i.e. "".
Also, it will fail if all the characters in str are value ch, i.e.
char buf[32] = "aaaaaaa";
trim(buf,'a') ;

... and it finds the first "ch" after first "non-ch" not the first of a
conscutive run of "ch" at the end of str as - the original code clearly
intended.

Because this function returns a pointer other than the one it was passed
if the storage is malloced it can't be freed with out holding onto the
original pointer somewhere else making it complicated to use in some
situations.

Somewhat similiar to the "complicate d" use of function realloc.
Example:
buf = realloc(buf, size)
intead of
char *tmp = realloc(buf,siz e)

More troublesome to me is that function trim as defined above, must
have synopsis saying to not use the function if the str is an
empty string, or if str consists entirely of characters ch.
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 15 '05 #8


jo******@hotmai l.com wrote:

[snip code]
the problem is that it always removes the last letter of str as well.
i.e.
" stuff " -> "stuf" any ideas why this is happening.
Cheers
John


Huh. I'm not getting that result based on the same test data (" stuff
"). You sure that's the code you're actually running?

Nov 15 '05 #9
jo******@hotmai l.com wrote:

have a bit of c code that is ment to take a string (that may or
may not have spaces before or after the string) i.e. " stuff ",
and trims off the whitespace before and after.
Code:

char *trim (char *str, char ch)


Untested:

char *trim(char *s, char ch)
{
char *p;

if (s && *s && ch) { /* avoid evil cases */
while (ch == *s) s++; /* trims leading. */
p = s; /* must be advanced over entry */
while (*p) p++; /* find end of string */
p-- /* last char in string */
while ((p > s) && (ch == *p)) p--;
*p = '\0';
}
return s; /* ok in evil cases */
}

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2351
by: Mar Thomas | last post by:
I have a dom tree created from an XML document but it shows whitespaces as Textnodes!! Pls tell me how to get rid of them I tried ... factory.setIgnoringElementContentWhitespace(true); but it doesnt work! Help me please thanks
0
1311
by: Prawdziwa Blondynka | last post by:
Hi, I would like to do the following with C++ and Xerces: set the schema path in an XML file to parse in this way: XMLCh* schemaLocation = XMLString::transcode(namespaceAndPath); //namespaceAndPath stands for the namespace and schema path containing whitespaces parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,
12
17098
by: Stefan Weiss | last post by:
Hi. (this is somewhat similar to yesterday's thread about empty links) I noticed that Tidy issues warnings whenever it encounters empty tags, and strips those tags if cleanup was requested. This is okay in some cases (such as <tbody>), but problematic for other tags (such as <option>). Some tags (td, th, ...) do not produce warnings when they are empty.
1
1766
by: Dave | last post by:
Hi Have a method that builds and returns a of specfic accounting codes to a datagrid textbox field. eg, if a user types in "200" the method builds & returns the code "200.00.00". also if a user types in "51" the method should return " 51.00.00" but I am finding difficulty adding a white space infront of the string, I have been using the PadLeft method eg: sCode = sCode.PadLeft(1, ' ') + ".00" + ".00";
1
2288
by: asjad | last post by:
Is there is any way that i can show whitespaces in my editor, made by extending rich text box.
0
1204
by: Paul | last post by:
On my local site, I have a folder that is security trimmed, so that only members of a Role can see it after they register and log on (I set the memberships). All works fine locally. However, when I deployed to my ISP, the security trimming does not work. Here is the relevant code. I can add users just fine, they show up in the ISP SQL Server database, and I can log on and off.
1
1697
by: rj | last post by:
Hello, I try to remove whitespaces from a string using the preg_replace function like preg_replace("/*/"," ",$string); This works great, but makes no handles all characters in the same way. I want to preserve data between double quotes. So, hello world "It is a sunny... world"
2
1679
by: rn5a | last post by:
When a Button is clicked in a Form, the JavaScript 'prompt' dialog pops-up for users to enter any text. When the user clicks OK in the prompt dialog, the text is populated in a TextBox & the Form posts. I then retrieve the text using Request.Form. The problem I am facing is in retaining whitespaces in the text the user has entered. Assume that the user has entered the following text in the JavaScript prompt dialog (note the whitespaces...
5
2322
by: mishink7 | last post by:
i was wondering how would u remove multiple whitespaces from the middle of a string to make it only one white space...for example: string hi= "hi bye"; then remove the multiple whitespaces in middle to make it "hi bye" any help would be appreciated...thanks.
0
8459
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8374
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8890
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8791
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
5677
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2018
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1783
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.