[英]How to convert a string to array of strings made of characters in c++?
如何將字符串拆分為每個字符的字符串數組? 例子:
INPUT:
string text = "String.";
OUTPUT:
["S" , "t" , "r" , "i" , "n" , "g" , "."]
我知道存在 char 變量,但在這種情況下,由於我正在使用的軟件類型,我確實需要一個字符串數組。
當我嘗試這樣做時,編譯器返回以下錯誤:
Severity Code Description Project File Line Suppression State
Error (active) E0413 no suitable conversion function from "std::string" to "char" exists
這是因為C++將stringName[index]視為char ,並且由於數組是字符串數組,因此兩者不兼容。 這是我的代碼:
string text = "Sample text";
string process[10000000];
for (int i = 0; i < sizeof(text); i++) {
text[i] = process[i];
}
有沒有辦法正確地做到這一點?
如果要制作字符串,則應查看字符串構造函數。 有一個適合你(我鏈接到的列表中的#2)
for (int i = 0; i < text.size(); i++) {
process[i] = string(1, text[i]); // create a string with 1 copy of text[i]
}
您還應該意識到sizeof
不會讓您獲得字符串的大小 使用size()
或length()
方法。
您還需要以正確的方式獲取text
和process
,但我想這只是一個錯字。
std::string
首先是一個容器,因此您可以對容器執行的任何操作,都可以對std::string
的實例執行。 我會在這里使用std::transform
:
const std::string str { "String." };
std::vector<std::string> result(str.size());
std::transform(str.cbegin(), str.cend(), result.begin(), [](auto character) {
return std::string(1, character);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.