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


原文链接: https://www.cnblogs.com/shendaw/p/17104656.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    String

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/316881

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 下午2:24
下一篇 2023年2月16日 下午2:27

相关推荐