Archived

This topic is now archived and is closed to further replies.

Ragadast

Help with Strings

Recommended Posts

Anyone knows a good tutorial about all the string functions? I''m trying to figure out how to do several things with strings in C++, but I don''t know their functions. I''m trying things like check a string character per character and then modify it.

Share this post


Link to post
Share on other sites
Using strings in C++ is easy, provided you''re using C++ strings and not C strings. C++ strings are encapsulated in a class provided by the C++ Standard Library while C strings are merely null-terminated char arrays, with a bunch of external functions for manipulating them.

Here''s how you use C++ strings:

#include <iostream>
#include <string>
 
int main( void )
{
using namespace std;
 
string str = "This is a string.";
cout << str << endl;
return 0;
}

That assigns and prints out the value of a string. What''s with the using namespace std thingie? The standardized C++ library headers place all their classes, objects and symbols within the std namespaces (namespaces are a method to resolve naming collisions - essentially to allow you freely write functions with any signature without fear of another function being identical, which results in linker errors).

Say we wanted to get a string from the user (one word) and count the number of occurences of a single letter in it, here''s what we might do:

#include <iostream>
#include <string>
 
int main( void )
{
using namespace std;
 
char ch;
string str;
cout << "Please enter a _single word_ to scan: ";
cin >> str;
cout << "Enter the letter to scan for: ";
cin >> ch;
 
int n = 0, len = str.size(), count = 0;
for( ; n < len; ++n )
if( str[n] == ch )
++count;
 
cout << "The letter " << ch << " was found " << count << " times in the word " << str << endl;
return 0;
}

But what if we wanted more than one word? What if we wanted to get a whole line of text? We''d use the getline function that is overloaded for strings:

#include <iostream>
#include <string>
 
int main( void )
{
using namespace std;
 
string str;
cout << "Enter a line of text: " << endl;
getline( cin, str );
cout << "The text you entered was:\n" << str << endl;
return 0;
}

Well, that''s a very simple and rudimentary primer on using strings. Check your compiler documentation for more information on the string class (string is a typdef for basic_string<char>, so your docs may only have a basic_string entry). MSDN and SGI also have good documentation (the SGI documentation is excellent, but not exactly beginner-friendly); both links are in my signature.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ ]
[ MS RTFM [MSDN] | SGI STL Docs | Boost ]
[ Google! | Asking Smart Questions | Jargon File ]
Thanks to Kylotan for the idea!

Share this post


Link to post
Share on other sites