Friday, August 26, 2011

Strings 101 - Part IV


The string insert() method.

This method allows you to insert one string inside another. There are many versions of this method but we'll only use two of them.

The following program illustrates how to insert one string s1, into another s2.

Example 1
string s1 = " hello ";
string s2 = "123456789";

string s3 = s2.insert(3, s1);

cout << s3 << endl;

This program prints the following:


Notice from the output that the string s1, "hello" is inserted inside the string s2, "123456789" so that s3 becomes "123hello456789"

Here's another example, in this case, we're using a different version of the insert() method. This one inserts a single character a number of times into a string.

Example 2:
string s1 = "123456789";
char c = 'x';

string s3 = s1.insert(3,10,c);

cout << s3 << endl;

This one prints the following:


Notice that the output this time is "123xxxxxxxxxx456789". The character 'x' was inserted at position 3 into the string s1.

Monday, December 13, 2010

Strings 101 - Part III Exercises

The string length() method.

In the last exercise we learnt that if we have a string, s, we can obtain it's length by calling it's length() method. From now on, we'll use the word method when referring to a function that's a member of a class. In the previous lesson, getline(), is a method of the cin iostream class.

Example 1
    string s;
    int i;

    s = "this is a string";
    i = s.length();

In the example above, s is a string. The value of s is: this is a string.

In the second line, i is declared as an integer, a whole number. The statement: i = s.length() assigns the value of s.length() to the integer, i.

The value of i is therefore 16.

  1. Write a program that asks the user for their name, displays their name and the length of the name.
     
  2. Write a program that asks the user to type in two lines. Display both lines of text and then determine which one is longer, the first line typed in, or the second one.
     
  3. Write a program that asks the user to type in a single word. Change the word from a lower-case word to an upper-case word. Assuming the ASCII character set only, the lower-case 'a' is ASCII 97 and the upper-case 'A' is ASCII 65. The lower-case 'z' is ASCII 122 and the upper-case 'Z' is ASCII 90. An individual string letter can be referenced by it's index. If s is a string, then s[0] is the first letter in the string. s[1] is the second letter in the string, and so on.
     
  4. Write a program that reads a line of text from the user, encrypts the string by changing each letter in the string with the one immediately after it in the ASCII table. Lower-case 'a' is replaced by lower-case 'b'. Upper-case 'X' is replaced by upper-case 'Y'. and so on.

Possible solutions will be posted in a later lesson.

Strings 101 - Part III

Obtaining the length of a string. Using the length() string method.

This tutorial is about processing character strings using C++. Specifically, it's about using the Standard Template Library (STL) string library.

The STL is a library of classes, algorithms and iterators provided as part of a complete C++ installation that simplify programming tasks. The STL provides templates for vectors, algorithms for searching and sorting, and iterators to help traverse lists and sequences. The STL is an extremely valuable library containing some of the most useful data structures and algorithms in computer science.

In this tutorial, we will concentrate on only one of them, the string library.

As you saw in the last section, to use the string library in C++ you need to reference it using the following code:

#include <string>  

We also included the <iostream> library in our code. That library allowed us to use the cout function to write output to the console.

The STL string library (or class) contains many useful functions and we will explore the following ones:

lengthdetermines the length of the string
insertinsert a string inside another one
eraseremove characters from a string
replacereplace a portion of a string with another string
findsearch for a portion of a string
substrextract a portion of a string
+=append to the string
comparecompare two strings

Let's start with a simple example. This program prompts the user from some input, echoes the input that the user typed in, as well as the number of characters in the input.

To obtain input from the user, we'll use the iostream function cin and it's member function getline. Here's the full program. Type it in and save it as s2.cpp.

File s2.cpp
#include <iostream>
#include <string>
using namespace std;

int main()
{
    char buffer[256];
    string s;

    cout << "Type in some text: ";
    cin.getline(buffer, 256);

    s = buffer;

    cout << "You typed in: " << s < < endl;
    cout << "There are " << s.length() << " characters in your text" << endl;

    return 0;
}

Analysis:

The first three lines should be familiar.

#include <iostream>
#include <string>
using namespace std;

These add the <iostream> and <string> libraries to our program. We also specify that we are in the std namespaces which means that functions are assumed to be in the std namespace unless we specifically state that they aren't. This is a little confusing so we'll say more about namespaces later.

The next part of the program is the entry point:

int main()

Every C++ program has a main() function.

The next two statements declare two variables that we're going to use:

char buffer[256];
string s;

The char buffer[256] declaration requests a character array that's 256 characters long. We're going to use this to collect the input that the user types in. The function that we'll use cin.getline() expects to put it's input in a character array, so we've declared one for this purpose. We specify that the maximum number of characters that this array can hold is 256 characters.

The next declaration, string s, is our string variable, or object.

The next two lines request the user to type something, and then collect what's typed in:

cout << "Type in some text: ";
cin.getline(buffer, 254);

The next line copies the text that's typed in from the character buffer[] array where it was stored, to our string object.

s = buffer;

Finally, we'll display what was typed in and also the number of characters that were typed in.

cout << "\n\nYou typed in: " << s << endl;
cout << "There are " << s.length() << " characters in your text" << endl;

The interesting function is:

s.length()

The function, or in object-oriented lingo, method, length() returns the length of the object.

In this case, the statement s.length() effectively returns the length of the string, s.

Finally, a return statement to indicate that everything was successful. Remember that returning the value of zero indicates no errors, success.

Saturday, December 11, 2010

Strings 101 - Part II

In the first part, [Strings Part I] we saw what strings were. In this second part, we'll write a small C++ program that uses strings.

All our programs will be created using a simple text editor. In Windows you can use Notepad or install a different text editor. On the Mac and in Linux, I prefer to use VIM.

You'll need a C++ compiler. In Windows, you can download Visual Studio Express Edition from Microsoft's web site. It comes with a command line compiler that you can use. Since I don't want to complicate things by adding notes on what to do, I'll leave this one up to you!

On Linux, and on my Mac, gcc/g++, are easily installed. On both these systems it requires installing developer tools. For the Mac, you only need to install the Xcode developer tools that are supplied free of charge with every Mac operating system. At least since the OS X flavour of Mac OS.

OK... lots of words, no code yet. So here we go. Create a file and call it s1.cpp. The contents of s1.cpp are:

File: s1.cpp


#include <iostream>
#include <string>

using namespace std;

int main() {
    string s = "Hello World!";
    cout << s << endl;   
    return 0; 
}



Explanation:

C++ is a small programming language. It lacks built-in ability to do a number of high level processing tasks automatically. For example, if you have a string "abcd," C++ has no built-in method to let you know how many characters are in that string. You'd have to count them.

But this lack of built-in features is one of C++'s strengths. It allows programmers to add this by writing their own libraries of routines to do this work. These libraries can then be shared. Some of them are even part of the basic C++ language specification now because they are so important.

#include <iostream>
This adds the iostream library to our program. The iostream library provides functions that allow us to read and write from the console, or command prompt.

#include <string>
This adds the string library to our program. The string library is the focus of this tutorial series and collects a number of useful features that simplify how C++ handles strings.

using namespace std;
I won't go into namespaces, however, it's important to note that the main idea behind namespaces is to avoid name clashes. For example, if another programmer wrote a library of string functions which had similar ones provided by the <string> library we declared in our program, we'd still be able to use our string library and the one designed by this other programmer. Namespaces will make sure that similar names in both libraries don't cause confusion.

Finally, our program.

int main() {
All our programs will have a main() function. As the names indicates, this is the entry point to the program. All processing begins here.

string s = "Hello World!";
This line declares a string object and initialises it to the value "Hello World!"

To declare a variable in C++, you begin by writing the variable type name. The variable type name indicates the type of data you want to store. In our case, we declared the name string to indicate that we would like to store string objects. We gave our string object the name "s."

cout << s << endl;
This next line uses the function cout to send, or display, the contents of the string object, s, to the screen. cout stands for "console output."

return 0;
This line returns a status back to the operating system. It's standard to return a value of zero when everything is OK. Returning a value to the operating system is important since it allows programs to be chained together intelligently and larger programs built by using smaller programs. In our case we have to return a value since at the top of the program we wrote -- int main(). This said that we were going to return an integer, or whole number, value.

Once you've finished writing the program, it's time to compile it and run it. On the Mac, or in Linux, all you do is type in the following command in the same folder location as the source code you just wrote.

g++ -o s1 s1.cpp

This calls the g++ compiler to create the object, or binary, version of the program s1.cpp. The -o tells the g++ compiler to name the resulting program "s1."

To execute the program, on a Mac or Linux, type the following:

./s1

That's it for this part.

Strings 101 - Part 1

String = sequence of characters.

In C++ a string is more than one character even though a single character can be identified as a string. We'll clear this up later.

Examples:

"abcdefghijklmnopqrstuvwxyz"
"12345678910"
"*%4_0a^abcdYYY#@"

Notice that in C++, strings are identified by the quotes " around the characters. C++ uses the double quote (") for strings

A character is identified in C++ using single quotes.

Examples:

'a'
'b'
'1'
'8'

Each character is identified by single quotes. In C++, you are not allowed to have more than one character inside the single quotes.

A string, however, can have more than one character. It can even have a single character, however, to identify it as a C++ string, you have to use double quotes.

"a" -- This is a string
'a' -- This is a single character