473,804 Members | 3,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterating through a string

Hi Guys,

I have a string which contains data elements separated by spaces. I also
have a function which returns the number of characters from the beginning of
the string for a given number of spaces. I am using a loop with strchr for
the number of spaces, and I was just wondering if there was a more efficient
(ie faster) way of achieving this. Any ideas please? Current function code
below:

int GetNewPosition( const std::string& DataStr, const int Spaces)
{
int i = 0; // space counter
char* b = const_cast<char *>(DataStr.c_st r()); // beginning of string

do {
b = strchr(b, ' '); // find next space
++i; ++b; // increment space counter and pointer
} while(i<Spaces && b != NULL);

if(b) return b - DataStr.c_str() ;
else return -1;
}
Any help is appreciated,
Thanks for reading,
Steve.
Jul 22 '05
16 4354

"Steve" <st*******@hotm ail.com> wrote in message
news:Ohrxc.1911 $ud5.1728@newsf e4-gui...
Hi Guys,

I have a string which contains data elements separated by spaces.


You could break it apart using strtok()
Jul 22 '05 #11
Thanks folks,

This exercise just tells me no matter how long I think I've been doing C++,
I'll always be a n00b! Fancy overlooking the "case of NULL", D'Oh!!

Thanks for the code advice too, it's appreciated...t hough I'm beginning to
think It'd be better for the world if I gave up programming ;)

Steve.
"Steve" <st*******@hotm ail.com> wrote in message
news:Ohrxc.1911 $ud5.1728@newsf e4-gui...
Hi Guys,

I have a string which contains data elements separated by spaces. I also
have a function which returns the number of characters from the beginning of the string for a given number of spaces. I am using a loop with strchr for
the number of spaces, and I was just wondering if there was a more efficient (ie faster) way of achieving this. Any ideas please? Current function code
below:

int GetNewPosition( const std::string& DataStr, const int Spaces)
{
int i = 0; // space counter
char* b = const_cast<char *>(DataStr.c_st r()); // beginning of string

do {
b = strchr(b, ' '); // find next space
++i; ++b; // increment space counter and pointer
} while(i<Spaces && b != NULL);

if(b) return b - DataStr.c_str() ;
else return -1;
}
Any help is appreciated,
Thanks for reading,
Steve.

Jul 22 '05 #12

With regard to the first comment I originally posted, I thought there might
be a solution
using streams to parse the words out of a string, I looked a bit closer,
below is
my attempt. This works fine apart from one detail, perhaps somebody might
jump in, there doesn't seem to be a way to specify the separator chars of
the original stream, in the example, the last word is returned as "dog." not
"dog"
Other than that, its a wonderfully simple snippet of code, praise to STL!

I've not benchmarked this code, but I presume its going to be relatively
efficient
since the iterator will maintain the position in the stringstream as the
words are pulled out,
there will be some extra overhead I suspect from using the string class as
opposed to
plain characters, that's life.

The question is then, how to specify the separator/whitespace for the
stream.
#include <iostream>
#include <sstream>
#include <iterator>

using namespace std;
int main(int argc, char* argv[])
{
istringstream is("the quick brown fox jumped over the lazy dog.");

istream_iterato r<string> is_iter(is);
istream_iterato r<string> end;

for ( ; is_iter != end; ++is_iter)
{
string nextword = *is_iter;
cout << "next word is \"" << nextword << "\"\n";
}
return 0;
}

"Steve" <st*******@hotm ail.com> wrote in message
news:Ohrxc.1911 $ud5.1728@newsf e4-gui...
Hi Guys,

I have a string which contains data elements separated by spaces. I also
have a function which returns the number of characters from the beginning of the string for a given number of spaces. I am using a loop with strchr for
the number of spaces, and I was just wondering if there was a more efficient (ie faster) way of achieving this. Any ideas please? Current function code
below:

int GetNewPosition( const std::string& DataStr, const int Spaces)
{
int i = 0; // space counter
char* b = const_cast<char *>(DataStr.c_st r()); // beginning of string

do {
b = strchr(b, ' '); // find next space
++i; ++b; // increment space counter and pointer
} while(i<Spaces && b != NULL);

if(b) return b - DataStr.c_str() ;
else return -1;
}
Any help is appreciated,
Thanks for reading,
Steve.

Jul 22 '05 #13
In article <2i************ @uni-berlin.de>,
"John Harrison" <jo************ *@hotmail.com> wrote:
"Steve" <st*******@hotm ail.com> wrote in message
news:Ohrxc.191 1$ud5.1728@news fe4-gui...
Hi Guys,

I have a string which contains data elements separated by spaces. I also
have a function which returns the number of characters from the beginning

of
the string for a given number of spaces. I am using a loop with strchr for
the number of spaces, and I was just wondering if there was a more

efficient
(ie faster) way of achieving this. Any ideas please? Current function code
below:

int GetNewPosition( const std::string& DataStr, const int Spaces)
{
int i = 0; // space counter
char* b = const_cast<char *>(DataStr.c_st r()); // beginning of string

do {
b = strchr(b, ' '); // find next space
++i; ++b; // increment space counter and pointer
} while(i<Spaces && b != NULL);

if(b) return b - DataStr.c_str() ;
else return -1;
}

Your current function is bugged. If there are no spaces, then b == NULL,
then you increment b, then you test it for NULL. That isn't going to work.
You also have a completely gratuitous const_cast in your code.

It's quite a good example of how newbies worry about efficiency without
other more important considerations such as writing working code, and
writing clear code.

However strchr is probably the fastest way to do it, however as with all
these questions there is no official answer as to which method is fastest.
The C++ standard makes no mention of which functions or techniques are
faster than others, the only way to tell for sure is try different methods
and time them.

Here's my version, completely untested, so apologies in advance for any
bugs.

int GetNewPosition( const std::string& DataStr, int Spaces)
{
const char* start = DataStr.c_str() ;
const char* p = start;
for (int i = 0; i < Spaces; ++i)
{
if (p == NULL)
return -1;
p = strchr(p + 1, ' ');
}
return p - start;
}


I suspect your code above doesn't do what the OP wanted...

GetNewPosition( "", 0) should return -1 if I understand what he is trying
to do, yours returns 0. Care to try again? :-)
Jul 22 '05 #14
In article <S-*************** *****@comcast.c om>,
"Dave Townsend" <da********@com cast.net> wrote:

With regard to the first comment I originally posted, I thought there might
be a solution
using streams to parse the words out of a string, I looked a bit closer,
below is
my attempt. This works fine apart from one detail, perhaps somebody might
jump in, there doesn't seem to be a way to specify the separator chars of
the original stream, in the example, the last word is returned as "dog." not
"dog"
That wasn't a requirement anyway.

Other than that, its a wonderfully simple snippet of code, praise to STL!

I've not benchmarked this code, but I presume its going to be relatively
efficient
since the iterator will maintain the position in the stringstream as the
words are pulled out,
there will be some extra overhead I suspect from using the string class as
opposed to
plain characters, that's life.

The question is then, how to specify the separator/whitespace for the
stream.
Good question...

#include <iostream>
#include <sstream>
#include <iterator>

using namespace std;
int main(int argc, char* argv[])
{
istringstream is("the quick brown fox jumped over the lazy dog.");

istream_iterato r<string> is_iter(is);
istream_iterato r<string> end;

for ( ; is_iter != end; ++is_iter)
{
string nextword = *is_iter;
cout << "next word is \"" << nextword << "\"\n";
}
return 0;
}


Your idea skips over all whitespace, not just spaces as the OP's code
did. I don't know if he would have a problem with that or not...

Otherwise, this works just as well as my custom iterator. What I did
would only be useful if one also implemented op-- (so you could go both
forward and backward) and/or a non-const version of op* (so you could
replace words.)
Jul 22 '05 #15
"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2innbjFpab doU1@uni-
C++ should provide two overloads for strchr

const char* strchr(const char*, int);

and

char* strchr(char*, int);


Good point. Because the OP is using std::string it's clear he's using C++.

Jul 22 '05 #16

"Siemel Naran" <Si*********@RE MOVE.att.net> wrote in message
news:xN******** *************@b gtnsc05-news.ops.worldn et.att.net...
"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2innbjFpab doU1@uni-
C++ should provide two overloads for strchr

const char* strchr(const char*, int);

and

char* strchr(char*, int);
Good point. Because the OP is using std::string it's clear he's using

C++.


Posting to comp.lang.c++ should also mean C++, although that isn't always
the case. Some posters profess to be coding in a mysterious language called
C/C++.

john
Jul 22 '05 #17

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

Similar topics

12
11754
by: Matthew Wilson | last post by:
I'm playing around with genetic algorithms and I want to write a function that mutates an integer by iterating across the bits, and about 1 in 10 times, it should switch a zero to a one, or a one to a zero. I'm not sure how many bits are inside a python integer. The library reference says at least 32. I'm thinking about writing a function that eats integers and poops out lists of bools; and then I can iterate through that, and change...
28
1535
by: rbt | last post by:
Either I'm crazy and I'm missing the obvious here or there is something wrong with this code. Element 5 of this list says it doesn't contain the string 255, when that's *ALL* it contains... why would it think that??? import time ips = for ip in ips: if '255' in ip:
74
5099
by: Michael | last post by:
As if we needed another string reversal question. I have a problem with the following code, that I believe should work. int StringReverse(char* psz) { char *p = psz; char *q = psz + strlen(psz) - 1; while (p < q) {
7
1694
by: Dave Hansen | last post by:
OK, first, I don't often have the time to read this group, so apologies if this is a FAQ, though I couldn't find anything at python.org. Second, this isn't my code. I wouldn't do this. But a colleague did, got an unexpected result, and asked me why. I think I can infer what is occurring, and I was able to find a simple work-around. But I thought I'd ask about it anyway. I've been pushing Python at work for use as a scripting...
6
6062
by: Gustaf Liljegren | last post by:
I ran into this problem today: I got an array with Account objects. I need to iterate through this array to supplement the accounts in the array with more data. But the compiler complains when I try to modify the objects in the array while iterating through it. I marked the bugs in this code: // Loop through all previously added accounts foreach(Account a in a1) // a1 is an ArrayList { // If name and context is the same if(a.Name ==...
2
2168
by: Nick | last post by:
Hi all, Just a quick question. I have a class that exposes a number of fields (which are themselves custom types) through public properties. At run time, I have an object whom I'd like to check, is of same type as one of these fields. Is there a method or technique for iterating through a class's public properties, such as maybe using something from the reflection namespace?
4
2994
by: dustin.getz | last post by:
consider the following working loop where Packet is a subclass of list, with Packet.insert(index, iterable) inserting each item in iterable into Packet at consecutive indexes starting at index. i=0 while(i<len(packet)-4): if packet==Packet("01110"): packet.insert(i, "01111") i+=10 #skip the 5 bits inserted, and skip the 5 bits just checked bc overlap should not trigger insertion
5
1966
by: mikehulluk | last post by:
Ok, Imagine I have a class class C { }; ostream& operator<<(ostream& o, const C& c) { ...}
4
2823
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
13
1472
by: kj | last post by:
Is there a special pythonic idiom for iterating over a list (or tuple) two elements at a time? I mean, other than for i in range(0, len(a), 2): frobnicate(a, a) ?
0
9704
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
9572
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
10562
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
10319
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...
1
7608
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
6845
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
5508
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...
1
4282
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 we have to send another system
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.