String

5 ways to create an Array of String

  • Using Pointers
  • Using 2-D Array
  • Using the String Class
  • Using the Array Class
  • Using the Vector Class

Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of Strings in C++.

1. Using Pointers

#include <iostream>

const char* colors[4] = {"blue", "red", "green", "yellow"};  // const was added because string literals (literally, the quoted strings) exist in a read-only area of memory
for (int i = 0; i < 4; i++) { std::cout << colors[i] << std::endl;}

2. Using 2-D Array

#include <iostream>

char colors[][10] = {"blue", "red", "green", "yellow"};   // multidimensional array must have bounds for all dimensions except the first
for (int i = 0 ; i < 4; i++) { std::cout << colors[i] << std::endl;}

3. Using the String Class

The strings are also mutable.

#include <iostream>
#include <string>

std::string colors[] = {"blue", "red", "green", "yellow"};
for (int i = 0 ; i < 4; i++) { std::cout << colors[i] << std::endl;}

4. Using the Array Class

An array is a homogeneous mixture of data that is stored continuously in the memory space. The STL container array can be used to allocate a fixed-size array. It may be used very similarly to a vector, but the size is always fixed.

#include <iostream>
#include <string>
#include <array>

std::array<std::string, 4> colors {"blue", "red", "green", "yellow"};
for (int i = 0; i < 4 ; i++) { std::cout << colors[i] << "\n";}

5. Using the Vector Class

Both the number of strings and string contents are mutable.

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> colors {"blue", "red", "green"};
colors.push_back("yellow");
for (int i = 0; i < colors.size() ; i++) { std::cout << colors[i] << "\n";}

Tokenize (Split)

Tokenizing a string denotes splitting a string with respect to some delimiter(s).
4 Ways:

  • Using stringstream
  • Using strtok()
  • Using strtok_r()
  • Using std::sregex_token_iterator

1. Using stringstream


2. Using strtok()


3. Using strtok_r()


4. Using std::sregex_token_iterator


posted @ 2023-02-09 11:24  shendawei  阅读(24)  评论(0)    收藏  举报