問題描述
我知道這是一個很簡單的問題,但我只想一勞永逸地解決它
I know this is a quite easy problem but I just want to solve it for myself once and for all
我只想使用字符作為拆分分隔符將字符串拆分為數組.(很像 C# 著名的 .Split() 函數.我當然可以應用蠻力方法,但我想知道還有什么比這更好的方法.
I would simply like to split a string into an array using a character as the split delimiter. (Much like the C#'s famous .Split() function. I can of course apply the brute-force approach but I wonder if there anything better than that.
到目前為止,我已經搜索過并且可能最接近的解決方案是使用 strtok(),但是由于它不方便(將您的字符串轉換為字符數組等)我不喜歡使用它.有沒有更簡單的方法來實現這一點?
So far the I've searched and probably the closest solution approach is the usage of strtok(), however due to it's inconvenience(converting your string to a char array etc.) I do not like using it. Is there any easier way to implement this?
注意:我想強調這一點,因為人們可能會問為什么蠻力不起作用".我的蠻力解決方案是創建一個循環,并在其中使用 substr() 函數.但是,由于它需要 起點 和長度,因此當我想拆分日期時它會失敗.因為用戶可能將其輸入為 7/12/2012 或 07/3/2011,在計算/"分隔符的下一個位置之前,我可以真正知道長度.
Note: I wanted to emphasize this because people might ask "How come brute-force doesn't work". My brute-force solution was to create a loop, and use the substr() function inside. However since it requires the starting point and the length, it fails when I want to split a date. Because user might enter it as 7/12/2012 or 07/3/2011, where I can really tell the length before calculating the next location of '/' delimiter.
推薦答案
使用向量、字符串和字符串流.有點麻煩,但它確實有效.
Using vectors, strings and stringstream. A tad cumbersome but it does the trick.
#include <string>
#include <vector>
#include <sstream>
std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<std::string> seglist;
while(std::getline(test, segment, '_'))
{
seglist.push_back(segment);
}
這會產生與內容相同的向量
Which results in a vector with the same contents as
std::vector<std::string> seglist{ "this", "is", "a", "test", "string" };
這篇關于按字符拆分字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!