C++ string useful code examples

This is quick reference where I consolidated source code examples of string operations and manipulations that go beyond the direct use of the std::string library.

String manipulations

Trim white spaces

Eliminate spaces in the beginning and end of the string.

#include <string>
#include <iostream>

void trim(std::string& str)
{
	std::size_t pos = str.find_first_not_of(' ');
	str = str.substr(pos);
	pos = str.find_last_not_of(' ');
	str = str.substr(0, pos + 1);
}

int main(void)
{
	std::string str = "  some spaces to be trimmed   ";
	trim(str);
	std::cout << str << std::endl;
	/* ... */
	return 0;
}

Split string

Split a string into a vector of the substrings based on a separator char.

#include <string>
#include <iostream>

std::vector<std::string> split(std::string in, char separator)
{
	std::vector<std::string> out;
	
	std::size_t pos = in.find(separator);
	std::size_t len = in.length();
	
	while (pos + 1 < len) {

		std::size_t orig = pos + 1;	
		pos = in.find('/', orig);
		
		if (pos == std::string::npos) {
			if (orig < len) 
				out.push_back(in.substr(orig, len));

			return out;
		}
		
		out.push_back(in.substr(orig, pos-1));
	}

	return out;
}

int main(void)
{
  std::string path = "/products/id";
  std::vector<std::string> result = split(path, '/');

  std::cout << "The path components are:" << std::endl;
  for (auto& i : result)
    std::cout << i << std::endl;
}

Type conversions

Converting from string to other types and back to strings.

String to integer

To convert a string to an integer we can use the std::stoi() function.

#include <string>

int main(void)
{
	std::string num_str = "7";
	int num = std::stoi(num_str);
	/* ... */
	return 0;
}

String to float, double and long double

To convert a string to float, double and long double we can use the std::stof, std::stod and std::stold functions, respectively.

#include <string>

int main(void)
{
	std::string str = "1.123";

	float f = std::stof(str);
	double d = std::stod(str);
	long double ld = std::stold(str);
	/* ... */
	return 0;
}

Numeric value to a string

To convert a numeric value to a string we can use std::to_string function or use a std::stringstream.

#include <string>
#include <iostream>

int main(void)
{
	int num = 7;
	std::string str1 = std::to_string(num);
	
	std::stringstream sst;
	sst << num;
	std::string str2 = sst.str();

	std::cout << str1 << " = " << str1 << std::endl; 
	return 0;
}
0%