473,785 Members | 2,819 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 2461
"Servé Lau" <se***@detongis er.com> wrote in message
news:10******** *****@corp.supe rnews.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(bu f, '\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***@detongis er.com> wrote in message
news:10******** *****@corp.supe rnews.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*******@netn ews.proxy.lucen t.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*****@mindsp ring.com> wrote in message
news:40******** **@mindspring.c om...

....
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*****@mindsp ring.com> wrote in message
news:40******** **@mindspring.c om...

...
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
6755
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... this number is always changing as I have hundreds of thousand of pages of text on my site. Problem: - in my opinion this just not only look weird, but the variable "n" (number)
32
8859
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 something like string s = "blah"; int i = s.find_first_of('a'); /* returns 2, I presume? */ s.replace(i,0,"e"); Right? Is this the best way (assuming I haven't made some stupid error)? Is there a way to (easily!) get a character pointer from...
0
1465
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 several shorter queries. In general, how do you do that? The following query contains only fake contents(so that no policy will be violated), and it should show what's the long query I am talking about. Thank you, Siemel. Not sure why I can't...
4
6494
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 of the United States"; strchr will be successful if i am looking for the "U". It returns a
2
3102
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 parameter has the 'int' type. From my knowledge it is not even portable. On a machine where 'char' has the same size as an 'int' and where 'char' has the same
10
1899
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, 'b' to ter... ... 2nd string to to ter , 'b' to ter... ... here are the codes: ... int i, k; char str={"adevf", "dcdhn", "oledc", "brdca"}; char chr={'a', 'b', 'c'};
1
1722
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... so my program takes this average and gives me 2.0013 in the log file. After it uses this shorter version for other calculations.instead of my original 2.0013005 (It cuts it and well that should NOT be a problem, but because of the arithmetics I use....
3
1858
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 shorter? like put the etiquettes on the button froma string of '123+456-789*0Cr/' ? problem is the command and lambda-func for each button is different. self.btnDisplay = Button(self,text='1',command=lambda
4
1546
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
10324
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...
1
10090
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9949
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8971
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
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
5380
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2879
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.