(C++)数组的元素到字符串中

(c++) Elements of Array into String?

本文关键字:字符串 元素 C++ 数组      更新时间:2023-10-16

有人可以帮助我将char array[]的某些元素转换为String吗?我还在学习弦乐。

char input[40] = "save filename.txt";
int j;
string check;
for (int i = 0; input[i] != ''; i++)
{
   if (input[i] == ' ')
   {
      j = i+1;
      break;
   }
}
int index;
for (int m = 0; arr[j] != ''; m++)
{
    check[m] = arr[j];
    j++;
    index = m; //to store '' in string ??
}
check[index] = '';
cout << check; //now, String should output 'filename.txt" only 

字符串类有一个构造函数,该构造函数采用以 NULL 结尾的 C 字符串:

char arr[ ] = "filename.txt";
string str(arr);

//  You can also assign directly to a string.
str = "filename.txt";

std::string 的 ctor 有一些有用的重载,用于从 char 数组构造字符串。在实践中使用时,重载大致等效于以下内容:

  • 获取指向常量char的指针,即以空结尾的C字符串。

    string(const char* s);
    

    char数组必须以空字符结尾,例如 {'t', 'e', 's', 't', ''} .C++中的字符串文字总是自动以 null 结尾,例如 "abc"返回一个包含元素{'a', 'b', 'c', ''}const char[4]

  • 获取指向常量char和指定要复制的字符数的指针。

    string(const char* s, size_type count);
    

    与上面相同,但只会从char数组参数中复制count个字符数。传递的 char 数组不一定必须以 null 结尾。

  • 采用 2 个迭代器。

    string(InputIt first, InputIt last);
    

    可用于从一系列字符构造字符串,例如

    const char[] c = "character array";
    std::string s{std::next(std::begin(c), 10), std::end(c)}; // s == "array".