include <iostream>

As a C++ programmer, you know that a huge part of any software project involves working with text and string data. Whether you‘re building a word processor, analyzing log files, or creating a chatbot, you need powerful tools for searching, splitting, transforming and manipulating strings. Fortunately, C++ provides a rich set of built-in functions for string and character processing as part of its string library.

In this ultimate guide, we‘ll walk through all of the essential C string functions with clear explanations and real code examples. You‘ll learn how to determine the length of a string, copy and concatenate strings, search and replace substrings, convert between strings and numbers, change case, trim whitespace, and much more.

By the end of this post, you‘ll be a C string grand master, equipped with the knowledge to tackle even the most complex text processing tasks in your C++ projects. Let‘s dive in!

What are C strings?

Before we get into the string functions, let‘s clarify what we mean by a "C string". In C++, a string is simply an array of characters terminated by a null character (‘\0‘). You can define a string literal in code using double quotes:

char str[] = "Hello World!";

The string library provides a more convenient std::string class for working with strings as objects. Many of the same classic C string functions are methods of std::string.

Determining String Length

One of the most basic string operations is finding out how many characters are in a string. In C++, you can use the length() or size() method of std::string:

using namespace std;

int main() {
string str = "Hello World!";
cout << "String length: " << str.length() << endl;
}

Output:

String length: 12

Both length() and size() return the number of characters in the string, not including the terminating null character.

Copying Strings

To copy one string to another, you can simply use the assignment operator (=) with std:string:


string str1 = "Hello";
string str2 = str1;

After this, str2 will contain a copy of str1. For old-school null-terminated C strings, use the strcpy function:


char str1[] = "Hello";
char str2[10];
strcpy(str2, str1);

The first argument to strcpy is the destination string, and the second is the source string to copy from. Make sure the destination array has enough space to store the copied string!

Concatenating Strings

Joining two strings together, or concatenation, is another essential string operation. With std::string you can simply use the + or += operators:


string str1 = "Hello";
string str2 = "World";
string str3 = str1 + " " + str2;

Now str3 will contain "Hello World". To concatenate C-style strings, use the strcat function:


char str1[20] = "Hello";
char str2[] = "World";
strcat(str1, " ");
strcat(str1, str2);

Again, make sure the first argument string has enough space to hold the concatenated result.

Comparing Strings

To check if two strings are equal, you can use the == or != operators with std::string:


string str1 = "Hello";
string str2 = "World";

if (str1 == str2) {
cout << "Equal!" << endl;
} else {
cout << "Not equal!" << endl;
}

For C strings, use the strcmp function:


char str1[] = "Hello";
char str2[] = "World";

if (strcmp(str1, str2) == 0) {
cout << "Equal!" << endl;
} else {
cout << "Not equal!" << endl;
}

strcmp returns 0 if the strings are equal, a negative value if the first string comes before the second lexicographically, and positive if the second string comes first.

Converting Strings to Numbers

It‘s often necessary to convert string representations of numbers to actual numeric values. For this, you can use std::stoi (string to integer) or std::stod (string to double):


string str1 = "42";
string str2 = "3.14";

int num1 = stoi(str1);
double num2 = stod(str2);

cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;

Output:

num1 = 42
num2 = 3.14

Converting Numbers to Strings

To go the other direction and convert numbers to their string representation, use the std::to_string function:


int num1 = 42;
double num2 = 3.14;

string str1 = to_string(num1);
string str2 = to_string(num2);

cout << "str1 = " << str1 << endl;
cout << "str2 = " << str2 << endl;

Output:

str1 = 42  
str2 = 3.140000

Searching Strings

To find the position of a substring within a string, use the find method of std::string:


string str = "Hello World";
int pos = str.find("World");

if (pos != string::npos) {
cout << "Found at position: " << pos << endl;
} else {
cout << "Not found!" << endl;
}

Output:

Found at position: 6

find returns the index of the first occurrence of the substring, or string::npos if the substring is not found.

Replacing Substrings

To replace all occurrences of a substring with another string, use the std::string replace method:


string str = "Hello World";
str.replace(str.find("World"), 5, "Universe");

cout << str << endl;

Output:

Hello Universe

The first argument to replace is the starting index, the second is the number of characters to replace, and the third is the replacement string.

Getting Substrings

To extract a portion of a string, use the substr method:


string str = "Hello World";
string sub = str.substr(6, 5);

cout << sub << endl;

Output:

World

The arguments to substr are the starting position and length of the substring to extract. If you omit the second argument, it will return the rest of the string from the starting position.

Changing Case

To change the case of characters in a string, you can use the toupper and tolower functions in a loop:


string str = "Hello World";

for(int i = 0; i < str.length(); i++) {
str[i] = toupper(str[i]);
}

cout << str << endl;

Output:

HELLO WORLD  

Trimming Whitespace

To remove whitespace characters (spaces, tabs, newlines) from the start and end of a string, you can use a combination of find_first_not_of and find_last_not_of:


string str = " Hello World ";

int start = str.find_first_not_of(" \t\n\r\f\v");
int end = str.find_last_not_of(" \t\n\r\f\v");

string trimmed = (start == string::npos) ? "" : str.substr(start, end - start + 1);

cout << "|" << trimmed << "|" << endl;

Output:

|Hello World|

We search for the first and last characters that are not whitespace, then take the substring between those positions. The ternary expression handles the case where the string is all whitespace.

Wrapping Up

This covers all of the fundamental C++ string functions that you need to be productive. We learned how to find the length of strings, copy and combine them, compare and search inside them, convert them to and from numbers, manipulate case and whitespace, and extract substrings.

Whenever you‘re working on a C++ project that involves text processing, refer back to this guide and code examples. Try out the different functions and experiment with your own string manipulation challenges. Over time, using the string functions will become second nature.

With practice and experience, you‘ll be able to quickly write compact, efficient, and robust C++ code for any string processing task. Now get out there and start coding! Let us know in the comments what cool projects you build with your newfound C string mastery.

Similar Posts