473,503 Members | 1,692 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a shorter strchr

Sometimes I code like this:

char *p = strchr(buf,'\n');
if (p)
*p = 0;

But I've also seen the shorter expression:

buf[strcspn(buf, '\n')] = 0;

Are their advantages to the second one except shorter code?
Nov 14 '05 #1
8 2437
"Servé Lau" <se***@detongiser.com> wrote in message
news:10*************@corp.supernews.com...
Sometimes I code like this:

char *p = strchr(buf,'\n');
if (p)
*p = 0;

But I've also seen the shorter expression:

buf[strcspn(buf, '\n')] = 0;

Are their advantages to the second one except shorter code?


I can't think of any. strcspn might be a bit slower than strchr, because it
is designed to look for a set of characters in a string.

What you have in the second case is slightly wrong, a typo perhaps. strcspn
takes a constant character pointer as it's second argument.
So it should be:
buf[ strcspn(buf, "\n") ] = 0;

Nov 14 '05 #2
Spacen Jasset wrote:
char *p = strchr(buf,'\n');
if (p)
*p = 0;
[or...]buf[strcspn(buf, '\n')] = 0; Are their advantages to the second one except shorter code?
I can't think of any. strcspn might be a bit slower than strchr, because it
is designed to look for a set of characters in a string.


Indeed. Also, "shorter" is relative. What appears shorter to you may be
many times longer to the CPU. Just try to strike a reasonable balance
between terseness and readability. Another idiom is

if((p=strchr(buf, '\n')))
*p = 0;

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 14 '05 #3
nrk
Serv�Lau wrote:
Sometimes I code like this:

char *p = strchr(buf,'\n');
if (p)
*p = 0;

But I've also seen the shorter expression:

buf[strcspn(buf, '\n')] = 0;

Are their advantages to the second one except shorter code?


The call to strcspn is incorrect. It should be:
buf[strcspn(buf, "\n")] = 0;

One (likely inconsequential) difference is that the second call will always
write a null to the string. There might be some performance trade-offs as
strcspn will be scanning the string for a *set* of characters that it
shouldn't find, while strchr searches for exactly one character which is
considerably more straightforward. Also, as a style issue, I would
probably not go for embedding a function call like that into the index of
an array in the assignment statement.

-nrk.

--
Remove devnull for email
Nov 14 '05 #4
Spacen Jasset wrote:

"Servé Lau" <se***@detongiser.com> wrote in message
news:10*************@corp.supernews.com...
Sometimes I code like this:

char *p = strchr(buf,'\n');
if (p)
*p = 0;

But I've also seen the shorter expression:

buf[strcspn(buf, '\n')] = 0;

Are their advantages to the second one except shorter code?
I can't think of any.
strcspn might be a bit slower than strchr, because it
is designed to look for a set of characters in a string.


Conceptually, strcspn can be described as looping calls to strchr.

size_t strcspn(const char *s1, const char *s2)
{
const char *const p1 = s1;

while (strchr(s2, *s1) == NULL) {
++s1;
}
return s1 - p1;
}
What you have in the second case is slightly wrong,
a typo perhaps. strcspn
takes a constant character pointer as it's second argument.
So it should be:
buf[ strcspn(buf, "\n") ] = 0;


A briefer, more computationally intensive way of writing it would be:

strtok(buf, "\n");

--
pete
Nov 14 '05 #5
pete wrote:
char *p = strchr(buf,'\n');
if (p)
*p = 0;
[or]buf[strcspn(buf, '\n')] = 0;

[snip] A briefer, more computationally intensive way of writing it would be:

strtok(buf, "\n");


However, this is not readable at all since the intent is unclear and the
effect is merely a byproduct of the function's semantics.

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 14 '05 #6
In <c0*******@netnews.proxy.lucent.com> David Rubin <no****@nowhere.net> writes:
pete wrote:
A briefer, more computationally intensive way of writing it would be:

strtok(buf, "\n");


However, this is not readable at all since the intent is unclear and the
effect is merely a byproduct of the function's semantics.


I disagree: the return value being ignored, it is (or should be) OBVIOUS
that this function was called *exclusively* for its side effect(s).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #7
"pete" <pf*****@mindspring.com> wrote in message
news:40**********@mindspring.com...

....
A briefer, more computationally intensive way of writing it would be:

strtok(buf, "\n");


That does not work how the other methods do though. In particular, it would
not remove '\n' at the begining of the string. From the NetBSD man pages:

" The strtok() function returns a pointer to the beginning of each subse-
quent token in the string, after replacing the separator character
itself
with a NUL character. Separator characters at the beginning of the
string or at the continuation point are skipped so that zero length to-
kens are not returned. When no more tokens remain, a null pointer is
re-
turned."

Nov 14 '05 #8
Spacen Jasset wrote:

"pete" <pf*****@mindspring.com> wrote in message
news:40**********@mindspring.com...

...
A briefer, more computationally intensive way of writing it would be:

strtok(buf, "\n");


That does not work how the other methods do though.
In particular, it would
not remove '\n' at the begining of the string.


Good catch. Thank you.

--
pete
Nov 14 '05 #9

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

Similar topics

16
6703
by: Krakatioison | last post by:
My sites navigation is like this: http://www.newsbackup.com/index.php?n=000000000040900000 , depending on the variable "n" (which is always a number), it will take me anywhere on the site......
32
8806
by: ataru | last post by:
I want to find the position of a character in a string and replace it another if it is actually there, and I'd like the operation to be efficient. I'm assuming the "standard" way to do this is...
0
1451
by: jy2003 | last post by:
The query below is very long, and it takes about 5 seconds to get the result. Of course I am not happy with the 5 seconds, and I am wondering if I can get a better speed if I can break it into...
4
6408
by: David Warner | last post by:
Greetings! In looking into some C coding, I am looking for the C function that will search for multiple occurances of a same character in a string. For Instance: char str = "We the people...
2
3078
by: ts | last post by:
Hello all, Can somebody explain why strchr is declared the way it is? Here is the declaration: char *strchr(const char *s, int c); Mainly I do not understand why the second ...
10
1862
by: runsun | last post by:
four strings are in a 2-D array; use strchr to find characters a, b, c, respectively; search results are to be put in another 2-D arrray ter: results of searching 'a' in the 1st string go to ter,...
1
1707
by: Daikide | last post by:
I need average for my program. And I'm using it multiple time in my program. I'm doing this in PVSS: So say average float is 2.0013005 (FOR EXAMPLE) but the number in the end can be higher......
3
1846
by: skanemupp | last post by:
is there anyway to make this shorter? i hate having these big blocks of similar-looking code, very unaesthetic. maybe doesnt matter good-code-wise? anyway can i make some function that makes this...
4
1522
by: raylopez99 | last post by:
Please consider the below and how to make name references shorter-- there has to be a way. RL using System; namespace MyNamesSpace1 { class ManagerClass
0
7074
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...
1
6982
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5572
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5000
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4667
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...
0
3161
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...
0
1501
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
374
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...

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.