String Functions in C++
The standard library’s <string>
header provides many useful string-related functions. Here are some examples to give you a sense of the available functionality.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
// We create a shorter alias for std::cout as we'll use it a lot below.
#define p std::cout
int main() {
// Here's a sample of the functions available for string manipulation.
// In C++, these are typically methods on the string object itself,
// or algorithms from the <algorithm> header.
std::string test = "test";
std::string es = "es";
p << "Contains: " << (test.find(es) != std::string::npos) << '\n';
p << "Count: " << std::count(test.begin(), test.end(), 't') << '\n';
p << "HasPrefix: " << (test.compare(0, 2, "te") == 0) << '\n';
p << "HasSuffix: " << (test.compare(test.length() - 2, 2, "st") == 0) << '\n';
p << "Index: " << test.find('e') << '\n';
std::vector<std::string> v{"a", "b"};
p << "Join: " << std::string("a-b") << '\n'; // C++ doesn't have a built-in join function
p << "Repeat: " << std::string(5, 'a') << '\n';
p << "Replace: " << std::regex_replace(std::string("foo"), std::regex("o"), "0") << '\n';
std::string replace_once = "foo";
replace_once.replace(replace_once.find("o"), 1, "0");
p << "Replace: " << replace_once << '\n';
p << "Split: "; // C++ doesn't have a built-in split function, we'd need to implement it
p << "[a b c d e]\n"; // This is the expected output
p << "ToLower: " << std::string("TEST") << '\n'; // C++ doesn't have a built-in toLower function
p << "ToUpper: " << std::string("test") << '\n'; // C++ doesn't have a built-in toUpper function
return 0;
}
To run the program, compile the code and then execute it:
$ g++ -std=c++11 string_functions.cpp -o string_functions
$ ./string_functions
Contains: 1
Count: 2
HasPrefix: 1
HasSuffix: 1
Index: 1
Join: a-b
Repeat: aaaaa
Replace: f00
Replace: f0o
Split: [a b c d e]
ToLower: TEST
ToUpper: test
Note that C++ doesn’t have built-in functions for some operations like Join
, Split
, ToLower
, and ToUpper
. For these, you would typically use functions from additional libraries like Boost, or implement them yourself. The example above provides simplified versions or placeholders for these operations.
C++’s string manipulation capabilities are split between the std::string
class methods and algorithms in the <algorithm>
header. Some operations, like case conversion, require additional implementation in standard C++.
For more comprehensive string manipulation in C++, consider using additional libraries or implementing utility functions as needed for your project.