473,769 Members | 2,106 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

std::string::np os always < std::string::si ze() ?

Is std::string::np os always going to be less than any std::string 's size()?

I am trying to handle a replacement of all occurances of a substr, in which
the replacement also contains the substr. Yick. All I could come up with is:

#include <string>

int main()
{
std::string text;
text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";

// Format the text
std::string formattedText(t ext);

// Change every occurrance of "\n" to "\r\n"
std::string::si ze_type index = 0;

do
{
index = formattedText.f ind('\n', index);
if( index != std::string::np os )
{
formattedText.i nsert(index, "\r");
index += 2;
}
} while( index < formattedText.s ize() );

// debugging contents of formattedText here

return 0;
}

However, it depends on std::string::np os always being less than the size of
the string and I am not certain whether that is safe or not.
Jan 10 '08 #1
11 4280
On Jan 10, 4:52 pm, "Christophe r Pisz" <some...@somewh ere.netwrote:
Is std::string::np os always going to be less than any std::string 's size()?

I am trying to handle a replacement of all occurances of a substr, in which
the replacement also contains the substr. Yick. All I could come up with is:

#include <string>

int main()
{
std::string text;
text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";

// Format the text
std::string formattedText(t ext);

// Change every occurrance of "\n" to "\r\n"
std::string::si ze_type index = 0;

do
{
index = formattedText.f ind('\n', index);
if( index != std::string::np os )
{
formattedText.i nsert(index, "\r");
index += 2;
}
} while( index < formattedText.s ize() );

// debugging contents of formattedText here

return 0;

}

However, it depends on std::string::np os always being less than the size of
the string and I am not certain whether that is safe or not.
I know this is a horrible solution, but what about something along the
lines copying the contents of the string to another string?
int i;

for (i = 0; i < string1.size(); i++)
{
if (string1[i] == '\n') string2 += "\r\n";
else string2 += string1[i];
}
It's slow and bloated it does the job in a straightforward way.
Jan 10 '08 #2
On Jan 10, 8:52*am, "Christophe r Pisz" <some...@somewh ere.netwrote:
Is std::string::np os always going to be less than any std::string 's size()?

I am trying to handle a replacement of all occurances of a substr, in which
the replacement also contains the substr. Yick. All I could come up with is:

#include <string>

int main()
{
* *std::string text;
* *text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";

* *// Format the text
* *std::string formattedText(t ext);

* *// Change every occurrance of "\n" to "\r\n"
* *std::string::s ize_type index = 0;

* *do
* *{
* * * index = formattedText.f ind('\n', index);
* * * if( index != std::string::np os )
* * * {
* * * * *formattedText. insert(index, "\r");
* * * * *index += 2;
* * * }
* *} while( index < formattedText.s ize() );

* *// debugging contents of formattedText here

* *return 0;

}

However, it depends on std::string::np os always being less than the size of
the string and I am not certain whether that is safe or not.
It is ok/safe. An std::string cannot have a length() (since it is
std::string, size()) greater than std::string::np os. So, your code
should be perfectly fine, it will always exit the do-while when all
instances of '\n' have been dealt with.
Jan 10 '08 #3
On Jan 10, 1:29*pm, Abhishek Padmanabh <abhishek.padma n...@gmail.com>
wrote:
On Jan 10, 8:52*am, "Christophe r Pisz" <some...@somewh ere.netwrote:


Is std::string::np os always going to be less than any std::string 's size()?
I am trying to handle a replacement of all occurances of a substr, in which
the replacement also contains the substr. Yick. All I could come up withis:
#include <string>
int main()
{
* *std::string text;
* *text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";
* *// Format the text
* *std::string formattedText(t ext);
* *// Change every occurrance of "\n" to "\r\n"
* *std::string::s ize_type index = 0;
* *do
* *{
* * * index = formattedText.f ind('\n', index);
* * * if( index != std::string::np os )
* * * {
* * * * *formattedText. insert(index, "\r");
* * * * *index += 2;
* * * }
* *} while( index < formattedText.s ize() );
* *// debugging contents of formattedText here
* *return 0;
}
However, it depends on std::string::np os always being less than the sizeof
the string and I am not certain whether that is safe or not.

It is ok/safe. An std::string cannot have a length() (since it is
std::string, size()) greater than std::string::np os. So, your code
should be perfectly fine, it will always exit the do-while when all
instances of '\n' have been dealt with.- Hide quoted text -

- Show quoted text -
Ideally, you should handle the length_error exception.
Jan 10 '08 #4
Christopher Pisz wrote:
Is std::string::np os always going to be less than any std::string 's
size()?
Actually, the other way around. std::string::np os is always going to be
greater than sny std::string's size.
I am trying to handle a replacement of all occurances of a substr, in
which the replacement also contains the substr. Yick. All I could
come up with is:
#include <string>

int main()
{
std::string text;
text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";

// Format the text
std::string formattedText(t ext);

// Change every occurrance of "\n" to "\r\n"
std::string::si ze_type index = 0;

do
{
index = formattedText.f ind('\n', index);
if( index != std::string::np os )
{
formattedText.i nsert(index, "\r");
index += 2;
}
} while( index < formattedText.s ize() );

// debugging contents of formattedText here

return 0;
}

However, it depends on std::string::np os always being less than the
size of the string and I am not certain whether that is safe or not.

Your code is perfectly fine, however, your while statment can simply be
changed to:

} while ( index != std::string::np os );

And you could even simplify it a bit by rearranging it.

index = 0;
while ( ( index = formattedText.f ind('n', index ) != std::string::np os )
{
formattedText.i nsert(index, "\r");
index += 2;
}

Now you don't need the if statmeent and to me it is cleaner code.
--
Jim Langston
ta*******@rocke tmail.com
Jan 10 '08 #5
On Jan 10, 4:52 am, "Christophe r Pisz" <some...@somewh ere.netwrote:
Is std::string::np os always going to be less than any
std::string 's size()?
It's always going to be greater.
I am trying to handle a replacement of all occurances of a
substr, in which the replacement also contains the substr.
Yick. All I could come up with is:
#include <string>
int main()
{
std::string text;
text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";
// Format the text
std::string formattedText(t ext);
// Change every occurrance of "\n" to "\r\n"
std::string::si ze_type index = 0;
do
{
index = formattedText.f ind('\n', index);
if( index != std::string::np os )
{
formattedText.i nsert(index, "\r");
index += 2;
}
} while( index < formattedText.s ize() );
// debugging contents of formattedText here
return 0;
}
However, it depends on std::string::np os always being less
than the size of the string and I am not certain whether that
is safe or not.
Your code should work, although I'd definitely use a while or a
for, rather than a do...while:

for ( size_t pos = text.find( '\n' ) ;
pos != std::string::np os ;
pos = text.find( '\n', pos + 2 ) ) {
text.insert( pos, '\r' ) ;
}

But generally, I'd rather not do this sort of thing in place.
Something more like:

std::string
convertToDos( std::string const& source )
{
std::string result ;
for ( std::string::co nst_iterator it = source.begin() ;
it != source.end() ;
++ it ) {
switch (*it) {
case '\n' :
result += "\r\n" ;
break ;

default :
result += *it ;
break ;
}
}
return result ;
}

This seems a lot cleaner to me, despite having more lines of
code, and is probably faster as well (less copying). If the
strings are very long, and performance is still a problem, you
can add the following after the definition of result:

result.reserve( source.size()
+ std::count( source.begin(), source.end(),
'\n' ) ;

. Unless the strings are very long, however, it probably won't
matter.)

--
James Kanze (GABI Software) mailto:ja****** ***@gmail.com
Conseils en informatique orient�e objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place S�mard, 78210 St.-Cyr-l'�cole, France, +33 (0)1 30 23 00 34
Jan 10 '08 #6
On Jan 10, 10:47 am, "Jim Langston" <tazmas...@rock etmail.comwrote :

[...]
And you could even simplify it a bit by rearranging it.
index = 0;
while ( ( index = formattedText.f ind('n', index ) != std::string::np os )
{
formattedText.i nsert(index, "\r");
index += 2;
}
Which has a nested assignment guaranteed to make the code more
difficult to read. As posted elsewhere, I'd do it with a for:

for ( size_t pos = formattedText.f ind( '\n' ) ;
pos != std::string::np os ;
pos = formattedText.f ind( '\n', pos + 2 ) ) {
formattedText.i nsert( pos, '\r' ) ;
}

Everything where a reader would expect to find it.
Now you don't need the if statmeent and to me it is cleaner code.
An assignment nested in a condition will never be considered
clean code. A statement should do one, and only one thing.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 10 '08 #7
James Kanze wrote:
On Jan 10, 10:47 am, "Jim Langston" <tazmas...@rock etmail.comwrote :

[...]
>And you could even simplify it a bit by rearranging it.
>index = 0;
while ( ( index = formattedText.f ind('n', index ) !=
std::string::n pos ) {
formattedText.i nsert(index, "\r");
index += 2;
}

Which has a nested assignment guaranteed to make the code more
difficult to read. As posted elsewhere, I'd do it with a for:

for ( size_t pos = formattedText.f ind( '\n' ) ;
pos != std::string::np os ;
pos = formattedText.f ind( '\n', pos + 2 ) ) {
formattedText.i nsert( pos, '\r' ) ;
}

Everything where a reader would expect to find it.
I would like others opionion on which they consider cleaner code.

I do ( var = something ) == something
all the time, and have always considered it clean.

Opinions?
>Now you don't need the if statmeent and to me it is cleaner code.

An assignment nested in a condition will never be considered
clean code. A statement should do one, and only one thing.
--
Jim Langston
ta*******@rocke tmail.com
Jan 10 '08 #8
Hi,

Use that all the time too, nothing wrong with it, in my opinion. But then
again every developer seems to have his/her own rules :-)
Regards, Ron AF Greve

http://www.InformationSuperHighway.eu

"Jim Langston" <ta*******@rock etmail.comwrote in message
news:OQ******** ****@newsfe06.l ga...
James Kanze wrote:
>On Jan 10, 10:47 am, "Jim Langston" <tazmas...@rock etmail.comwrote :

[...]
>>And you could even simplify it a bit by rearranging it.
>>index = 0;
while ( ( index = formattedText.f ind('n', index ) !=
std::string:: npos ) {
formattedText.i nsert(index, "\r");
index += 2;
}

Which has a nested assignment guaranteed to make the code more
difficult to read. As posted elsewhere, I'd do it with a for:

for ( size_t pos = formattedText.f ind( '\n' ) ;
pos != std::string::np os ;
pos = formattedText.f ind( '\n', pos + 2 ) ) {
formattedText.i nsert( pos, '\r' ) ;
}

Everything where a reader would expect to find it.

I would like others opionion on which they consider cleaner code.

I do ( var = something ) == something
all the time, and have always considered it clean.

Opinions?
>>Now you don't need the if statmeent and to me it is cleaner code.

An assignment nested in a condition will never be considered
clean code. A statement should do one, and only one thing.

--
Jim Langston
ta*******@rocke tmail.com

Jan 10 '08 #9
On Jan 10, 11:17 pm, "Jim Langston" <tazmas...@rock etmail.comwrote :
James Kanze wrote:
On Jan 10, 10:47 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
[...]
And you could even simplify it a bit by rearranging it.
index = 0;
while ( ( index = formattedText.f ind('n', index ) !=
std::string::np os ) {
formattedText.i nsert(index, "\r");
index += 2;
}
Which has a nested assignment guaranteed to make the code
more difficult to read. As posted elsewhere, I'd do it with
a for:
for ( size_t pos = formattedText.f ind( '\n' ) ;
pos != std::string::np os ;
pos = formattedText.f ind( '\n', pos + 2 ) ) {
formattedText.i nsert( pos, '\r' ) ;
}
Everything where a reader would expect to find it.
I would like others opionion on which they consider cleaner code.
I do ( var = something ) == something
all the time, and have always considered it clean.
Opinions?
In addition to opinions, there are measurable differences in
readability. When scanning the code rapidly, "if" or "while"
means flow control, not state change. Doing too many things in
a single statement leads to obfuscation.

Obviously, it's not an absolute rule, and must be weighed
against other "obfuscatio ns" that obeying it might introduce.
And there are idioms so ubiquious that they are recognized
despite breaking the rule: I write things like:
while ( std::getline( source, line ) ) ...
, for example, even though it violates the rule, because it is
so ubiquious that doing it any other way raises questions. I
would hope, however, that we're past the time when people
thought it clever to put the entire function in a single
condition---things like:
while ( *p ++ = *q ++ );
or even
while ( (*p ++ = *q ++) != 0 );
(The first is drawn from the original K&R, and even back then,
the authors expressed some doubts as to its advisability.)

In this particular case, there's absolutely no reason to "hide"
the update of index. Especially as you also have a specific
update at the end of the while, where people would normally look
for it: your loop looks like a classical "while" (which I would
normally write as a for), with update of the control variable at
the end of the loop, and then you sneek in an additional update
in the conditional expression.

In an ideal world, to find where a variable is being modified,
it would be sufficient to scan down the file looking at the
first token in each line. Obviously, that ideal isn't really
attainable, but you shouldn't have to search into the middle of
a complicated expression either.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 11 '08 #10

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

Similar topics

11
3662
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while( (idx=str.find_first_of(',')) >= 0 ) { str.replace( idx, 1, "" ); str.insert( idx, " or " ); }
25
2992
by: Jason | last post by:
Hi, below is example code which demonstrates a problem I have encountered. When passing a number to a function I compare it with a string's size and then take certain actions, unfortunately during the testing of it I discovered that negative numbers were being treated as if they were > 0. I compiled the following on mingw compiler/dev c++/windows xp. If I replace string.size() for a ordinary number it behaves as expected? I notice...
1
4408
by: Tero Toivanen | last post by:
Dear experts, I am doing code to Solaris 9 system with C++. I get every now and then segmentation fault in the following code that removes heading and trailing white spaces (mLineStr is of type std:string): ------
15
6905
by: roberts.noah | last post by:
Are there any decent benchmarks of the difference between using c strings and std::string out there? Google isn't being friendly about it. Obviously this would be dependant on different implementations but I don't care. I would be happy to find ANY comparison at this point if it was valid and semi scientifically done.
7
4869
by: Marcus Kwok | last post by:
std::string::npos is described in _TC++PL:SE_ (Section 20.3.4) as the "all characters" marker. I tried to use it this way, but my program crashes: #include <iostream> #include <string> int main() { std::string s = "hi/hello/now";
2
5511
by: FBergemann | last post by:
if i compile following sample: #include <iostream> #include <string> int main(int argc, char **argv) { std::string test = "hallo9811111z"; std::string::size_type ret;
10
9070
by: lovecreatesbea... | last post by:
Is it correct and safe to compare a string object with "", a pair of quotation marks quoted empty string?If the string object: s = ""; does s contain a single '\'? Is it better to use std::string::size or std::string::empty to deal with this condition? Thank you. string s = ""; if (s == ""); if (s.size == 0); if (s.empty());
8
2540
by: Marcus Kwok | last post by:
Is std::string::npos portably able to be incremented? For example, I want to insert some text into a string. If a certain character is found, I want to insert this text immediately after this character; otherwise I insert at the beginning of the string. On my implementation string::npos has the value of (string::size_type)-1, so incrementing it will make it 0, but can I rely on it? Also, say that the character occurs at the end of...
8
13765
by: Edson Manoel | last post by:
I have some C++ unmanaged code that takes std::string& arguments (as reference), and fills them (possibly growing the string). I want to call this code through PInvoke (DllImport), possibly using wrapper layers in unmanaged C++ and C#. I've thought about two approaches: 1) To pass a StringBuilder, this is converted to a char* in C++, the wrapper code converts the char* to a std::string (copy), and in the
0
9589
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
10049
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
9997
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
9865
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
8873
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...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
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
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.