简体   繁体   English

(c ++)数组元素成字符串?

[英](c++) Elements of Array into String?

Can somebody help me in converting some elements of char array[] into String . 有人可以帮助我将char array[]某些元素转换为String I'm still learning strings. 我还在学习弦乐。

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

The string class has a constructor that takes a NULL-terminated C-string: 字符串类具有一个采用NULL终止的C字符串的构造函数:

char arr[ ] = "filename.txt";

string str(arr);


//  You can also assign directly to a string.

str = "filename.txt";

The ctor of std::string has some useful overloads for constructing a string from a char array. std::string的ctor具有一些有用的重载,用于从char数组构造字符串。 The overloads are about equivalent to the following when used in practice: 在实践中使用时,重载大约等于以下内容:

  • Taking a pointer to constant char , ie a null-terminated C-string. 以指向常量char的指针,即以null终止的C字符串。

     string(const char* s); 

    The char array must be terminated with the null character, eg {'t', 'e', 's', 't', '\\0'} . char数组必须以空字符终止,例如{'t', 'e', 's', 't', '\\0'} String literals in C++ is always automatically null-terminated, eg "abc" returns a const char[4] with elements {'a', 'b', 'c', '\\0'} . C ++中的字符串文字总是自动以空值结尾的,例如"abc"返回带有元素{'a', 'b', 'c', '\\0'}const char[4]

  • Taking a pointer to constant char and specified number of characters to copy. 以指向常量char和指定字符数的指针进行复制。

     string(const char* s, size_type count); 

    Same as above but only count number of characters will be copied from the char array argument. 与上述相同,但只有count的字符数将从复制char数组参数。 The passed char array does not necessarily have to be null-terminated. 传递的char数组不一定必须以null终止。

  • Taking 2 iterators. 带有2个迭代器。

     string(InputIt first, InputIt last); 

    Can be used to construct a string from a range of characters, eg 可用于从一系列字符构造字符串,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM