๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

C++ Strings in Depth

String editing changes the text inside a std::string in place. Conversion functions turn text into numbers and numbers back into text.

Insert and erase in place

A string starts as Hello World. insert puts a comma after Hello, and erase then takes the comma back out.

#include <iostream>
#include <string>

int main() {
  std::string word = "Hello World";
  std::cout << word << "\n";
  word.insert(5, ",");
  std::cout << word << "\n";
  word.erase(5, 1);
  std::cout << word << "\n";
  return 0;
}

Replace swaps a span

replace starts at index 7 here. It removes three characters and puts the word coffee in their place.

#include <iostream>
#include <string>

int main() {
  std::string text = "I like tea";
  std::cout << text << "\n";
  text.replace(7, 3, "coffee");
  std::cout << text << "\n";
  return 0;
}

Numbers out of text

std::stoi reads 12 from the first string. std::stod reads 2.5 from the second string, and arithmetic runs on both results.

#include <iostream>
#include <string>

int main() {
  std::string countText = "12";
  std::string priceText = "2.5";
  int count = std::stoi(countText);
  double price = std::stod(priceText);
  std::cout << "Count plus 3: " << count + 3 << "\n";
  std::cout << "Double price: " << price * 2 << "\n";
  return 0;
}

Text out of numbers

std::to_string turns each number into text. The + signs join the pieces into one line.

#include <iostream>
#include <string>

int main() {
  int score = 90;
  int total = 100;
  std::string line = "Score: " + std::to_string(score) + " of " + std::to_string(total);
  std::cout << line << "\n";
  return 0;
}

Example

#include <iostream>
#include <string>

int main() {
  std::string item = "Notebook";
  std::string countText = "4";
  std::string priceText = "3";
  int count = std::stoi(countText);
  int price = std::stoi(priceText);
  std::string receipt = item + " x" + std::to_string(count) + ": " + std::to_string(count * price);
  std::cout << receipt << "\n";
  return 0;
}

Key points

  • insert adds characters at a chosen index inside a string.
  • erase removes a count of characters starting at an index.
  • replace swaps a span of characters for new text.
  • std::stoi reads a whole number from the start of a string.
  • std::stod reads a decimal number from the start of a string.
  • std::to_string turns a number into a string.

In this example, std::stoi reads the count 4 and the price 3 from text. std::to_string turns the count and the total 12 back into text. The joined pieces print as one receipt line.

Note

insert, erase, and replace change the string itself, not a copy.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does std::stoi("12") + 3 give?