Team 2550
Technical Documentation
 All Files Variables Pages
Strings

Strings are not as simple to use in C++ as they are in many other languages. This page provides information about how to work with strings.

C-strings

A c-string is simply a null-terminated array of characters. In other words, a c-string is an array of char variables containing an ASCII \0 character at the end.

Declaration

You have actually used c-strings already. Any time you placed text in quotes, the compiler treats it as an (anonymous) c-string. However, the C standard library also included some basic functions for manipulating such strings.

//Length: 6
//A null character is automatically inserted at the end.
char str1[] = "Hello";
//Length: 20
//Be very careful, if you assign a string longer than 1 - length,
// you will overwrite memory outside of the array bounds.
char str2[20] = "Hello";
//Length: 10
//This is another way to declare a c-string. It is not usually very useful.
// NOTE: using this method, you have to insert the null character.
char str3[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
//Initializing empty strings
char str4[10] = "";
char str5[10] = {0};
char str6[10] = {'\0'};
Warning
You always want to initialize c-strings (even if it is only a null character). If you don't, there will be problems when you try to run the c-string-related functions.

Printing

You can output a c-string with cout. The null termination allows it to determine exactly how long it is.

char str[] = "This is a test";
cout << str;

Outputs

This is a test

Functions

#include <cstring> provides various functions that can be used to manipulate c-strings.

Function Action Example
strlen(string) Returns the length of a c-string up to the first null character
char str[] = "Hello";
strlen(str);
//Result: 5
strcpy(destination, source) Copies the contents of one c-string into another
#include <cstring>
using namespace std;
int main() {
char str1[] = "string to copy";
char str2[100] = {0};
strcpy(str2, str1); //copies str1 into str2
}
strcat(destination, source) Merges two strings, the result is added to the end of the destination string.
char str1[] = "Hello";
char str2[100] = " world";
strcat(str1, str2);
//Result: "Hello world"
Warning
Be very careful with the length of these strings. It can be very easy to go out of bounds. Use strlen to make sure you will not go out of bounds.
strcmp(string1, string2)

Compares string1 and string2 lexographically.

Note
Lexographic comparison is not important at this point.

Returns

  • 0 if the strings are equal
  • Negative number if string1 is less than string2
  • Positive number if string1 is greater than string2
char str1[10] = "hello";
char str2[10] = "test";
strcmp(str1, str2); //Result: -12
strcpy(str1, "test");
strcmp(str1, str2); //Result: 0
strcpy(str2, "no");
strcmp(str1, str2); //Result: 6

strchr(string, character)

strrchr(string, character)

strchr: Finds the first occurence of a character in the string and returns the remaining substring.

strrchr: Finds the last occurence of a character in the string and returns the remaining substring.

Both return NULL if the character was not found.

strchr

char str[] = "hello";
strchr(str, 'l'); //Result: "llo"
strchr(str, '\n'); //Result: NULL

strrchr

char path[] = "/this/is/a/file/path/to/file.txt";
strchr(path, '/'); //Result: /file.txt
Note
If you are working on a Windows machine / would have to be replaced with \\
Warning
NULL cannot be printed via cout. Doing so will crash the program.
strstr(str, search) Searches for a substring in a string.
char str[] = "this is a test string";
strstr(str, "test"); //Result: "test string"
strncpy
strncat
strncmp
These functions are the same as their counterparts, strcpy, strcat, and strcmp. The only difference is that there is a third parameter which represents the number of characters upon which to perform the operation. For instance, strncpy will copy the first n characters from one string into another.
//Copy a part of a string into another, smaller, string.
char str1[] = "this is a test string";
char str2[10];
strncpy(str2, str1, 9);
// str2 = "this is a"
strlen(str2); //Result: 9
Warning
Do not copy the full length of one array into another. The NULL character will be written out of bounds.
Warning
It is very important to make sure that c-strings are null terminated. All of the above functions use the null character in order to determine the length of the string. They iterate through the array until a null character is reached.

I/O

The normal streaming operators work with c-strings. You can output with cout << and input with cin >>.

Warning
Using cin has one major problem. It is whitespace-delimited. The following code illustrates the problem.
char str[100];
cin >> str;

If the user inputs something with whitespace, such as

this is my input

cin will place the word "this" into str and leave the other words for later. In order to avoid this problem, you have to use cin.get. Problem solved.

char str[100];
cin.get(str, 100);

The cin.get(str, 100) line accepts up to 99 characters from the user, whitespace included, and writes it all into str.

std::string

C-strings work, but they can get complicated. The C++ standard library (the built-in tools that come with every C++ compiler) has a string datatype that manages c-strings for you. It is much easier to use, but there are also times where it can be less efficient.

Note
If the code is not made significantly more difficult to manage and understand using c-strings, don't use std::string.

A few of the benefits of std::string:

  • The length is managed automatically, no bounding issues
  • You can re-assign a string, no need to use a copy function in order to change the contents
  • Strings can be passed by value or reference
  • The normal comparison operators work

Basic String Manipulation

You don't need functions to do basic operations with strings. The normal arithmetic operators work.

Re-assigning

You can use the assignment = operator to change the value of a string.

#include <string> //defines the std::string datatype
using namespace std;
int main() {
string str = "hi";
str = "there";
}

The above code is valid. This would cause problems with c-strings.

Concatination

The + operator concatinates (combines) two strings.

string str1 = "ha";
string str2 = " ha";
string str3 = str1 + str2; //str3 = "ha ha"

You can also concatinate a string with a c-string.

string str = "he";
str += "llo"; //str = "hello"

Comparison Operators

==, !=, <, >, <=, and >= all work with strings. For now, only == and != are really useful.

string str1 = "not";
string str2 = "true";
bool equal = str1 == str2 ? true : false; //Result: false
Note
The above code is the same as saying...
//...
bool equal;
if (str1 == str2)
equal = true;
else
equal = false;

I/O

Again, cout << ... and cin >> both work with std::string variables. However, the same input problem exists when using cin >> (see c-string I/O). However, the solution is slightly different.

string str;
getline(cin, str); //Writes a line entered by the user to str
getline(cin, str, ','); //Changes the delimiter from a `\n` to a comma, allowing for the user to input multiple lines.

Methods

A method is a function that operates on a specific variable (such as a string). The format for calling a method is variable.method().

Method Action Example
at(index) Accesses a character in the string (array notation).
string str = "hello";
str.at(0) //Result: h
Note
You can also use the standard array notation.
str[1]; //Result: e
c_str() Returns an unmodifiable c-string. This can be useful for functions that take a c-string as an argument, for instance, opening files.
string str = "test";
str.c_str();
empty() Checks whether the string is empty.
string str = "";
str.empty(); //Result: true
size()
length()
Returns the length of the string.
string str = "this is a string";
str.size(); //Result: 16
clear() Erases the contents of the string.
string str = "this will be erased";
str.clear(); //str = "";
insert(index, substring)
insert(index, substring, count)
insert(index, count, character)
Adds a character or substring starting at the given index in a string without erasing data. count sets the number of times a character or substring is repatedly added.
string str = "forgot in this string";
str.insert(6, " something"); //str = "forgot something in this string"
str.insert(str.length(), 10, '.'); //str = "forgot something in this string.........."
erase(index, count) replace(index, count) substr(index, count)

Removes or replaces characters in the string. substr returns a substring in the range.

  • index: where to start
  • count: number of characters to remove after index
string str = "this is a string";
str.erase(5, str.length()); //str = "is a string"
Note
There are many more advanced methods available for string manipulation. For more information, see cppreference.com.