c语言字符串定界符,关于c ++:按字符分割字符串
我知道這是一個非常簡單的問題,但我只想一次為自己解決
我只想使用字符作為分割定界符將字符串分割成數組。 (很像C#著名的.Split()函數。我當然可以應用蠻力方法,但是我想知道是否有什么更好的方法了。)
到目前為止,我已經搜索過,也許最接近的解決方案是使用strtok(),但是由于不方便(將字符串轉換為char數組等),我不喜歡使用它。有沒有更簡單的方法來實現這一目標?
注意:我想強調這一點,因為人們可能會問:"蠻力為什么不起作用"。我的暴力解決方案是創建一個循環,并在其中使用substr()函數。但是,由于它需要起點和長度,因此在我想分割日期時會失敗。因為用戶可能輸入的時間是2012年7月12日或2011年7月3日,所以在計算" /"定界符的下一個位置之前,我可以真正說出長度。
拆分字符串C ++的可能重復項
使用向量,字符串和stringstream。有點麻煩,但可以解決問題。
std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<:string> seglist;
while(std::getline(test, segment, '_'))
{
seglist.push_back(segment);
}
導致向量的內容與
std::vector<:string> seglist{"this","is","a","test","string" };
實際上,這種方法正是我所尋找的。很容易理解,不使用外部庫,只是非常簡單。謝謝@thelazydeveloper!
如果要提高性能,可以添加seglist.reserve(std::count_if(str.begin(), str.end(), [&](char c) { return c == splitChar; }) + (str.empty() ? 1 : 0));如果要拆分的原始字符串存儲在str中。
喜歡RegEx的人的另一種方式(C ++ 11 / boost)。就我個人而言,我非常喜歡RegEx這類數據。 IMO比使用分隔符簡單地分割字符串要強大得多,因為您可以根據需要選擇對構成"有效"數據的內容更加了解。
#include
#include ? ? // copy
#include ? ? // back_inserter
#include ? ? ? ?// regex, sregex_token_iterator
#include
int main()
{
std::string str ="08/04/2012";
std::vector<:string> tokens;
std::regex re("\\d+");
//start/end points of tokens in str
std::sregex_token_iterator
begin(str.begin(), str.end(), re),
end;
std::copy(begin, end, std::back_inserter(tokens));
}
因此,您可以在代碼中包括整個正則表達式匹配器,僅用于拆分字符串。傷心...
@Dev否,包括一個正則表達式匹配器,以便對構成有效數據的內容更加智能-例如選擇數字,并允許使用其他分隔符,例如點或連字符
就二進制大小和整體效率而言,這都是不好的,但是由于這兩個原因都不涉及這種情況,因此我不再繼續。
@Dev如果一個人對二進制大小有如此極端的約束,那么他們甚至應該重新考慮使用C ++,或者至少使用它的標準庫(例如string / vector / etc),因為它們都會產生類似的效果。關于效率,最好的建議來自Donald Knuth-"過早的優化是萬惡之源";換句話說,在進行優化之前,首要任務是確定是否存在問題,然后通過諸如剖析之類的客觀手段來確定原因,而不是浪費時間試圖尋找每一個可能的微觀優化。
"在這種情況下,兩個人都不關心"-我自己。
@Dev然后我想知道什至提起它們的目的是什么。
我只是不想將整個正則表達式引擎用于查找整數。但是,如果您不想專門化代碼,這很好。
Boost具有您要在algorithm/string.hpp中查找的split():
std::string sample ="07/3/2011";
std::vector strs;
boost::split(strs, sample, boost::is_any_of("/"));
另一種可能性是使流具有使用特殊ctype構面的語言環境。流使用ctype構面確定什么是"空白",將其視為分隔符。使用將分隔符分類為空格的ctype構面,讀取結果可能非常簡單。這是實現方面的一種方法:
struct field_reader: std::ctype {
field_reader(): std::ctype(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector<:ctype_base::mask>
rc(table_size, std::ctype_base::mask());
// we'll assume dates are either a/b/c or a-b-c:
rc['/'] = std::ctype_base::space;
rc['-'] = std::ctype_base::space;
return &rc[0];
}
};
我們通過使用imbue告訴流使用包含它的語言環境,然后從該流中讀取數據來使用它:
std::istringstream in("07/3/2011");
in.imbue(std::locale(std::locale(), new field_reader);
設置好后,拆分幾乎變得微不足道-只需使用幾個istream_iterator初始化向量以從字符串(嵌入在istringstream中)讀取片段即可:
std::vector<:string>((std::istream_iterator<:string>(in),
std::istream_iterator<:string>());
顯然,如果只在一個地方使用它,則可能會導致過度殺傷。但是,如果您使用過多,則在保持其余代碼的整潔度方面可能要走很長的路要走。
我天生不喜歡stringstream,盡管我不確定為什么。今天,我編寫了此函數,以允許將std::string通過任意字符或字符串拆分為向量。我知道這個問題很舊,但是我想分享一種拆分std::string的替代方法。
盡管可以很容易地修改它以包括它們,但是該代碼完全省略了從結果中分割出的字符串部分。
#include
#include
void split(std::string str, std::string splitBy, std::vector<:string>& tokens)
{
/* Store the original string in the array, so we can loop the rest
* of the algorithm. */
tokens.push_back(str);
// Store the split index in a 'size_t' (unsigned integer) type.
size_t splitAt;
// Store the size of what we're splicing out.
size_t splitLen = splitBy.size();
// Create a string for temporarily storing the fragment we're processing.
std::string frag;
// Loop infinitely - break is internal.
while(true)
{
/* Store the last string in the vector, which is the only logical
* candidate for processing. */
frag = tokens.back();
/* The index where the split is. */
splitAt = frag.find(splitBy);
// If we didn't find a new split point...
if(splitAt == string::npos)
{
// Break the loop and (implicitly) return.
break;
}
/* Put everything from the left side of the split where the string
* being processed used to be. */
tokens.back() = frag.substr(0, splitAt);
/* Push everything from the right side of the split to the next empty
* index in the vector. */
tokens.push_back(frag.substr(splitAt+splitLen, frag.size()-(splitAt+splitLen)));
}
}
要使用,只需像這樣致電...
std::string foo ="This is some string I want to split by spaces.";
std::vector<:string> results;
split(foo,"", results);
現在,您可以隨意訪問向量中的所有結果。就這么簡單-沒有stringstream,沒有第三方庫,沒有回到C!
您對為什么會更好會有任何爭議?
看看boost :: tokenizer
如果您想匯總自己的方法,則可以使用std::string::find()確定拆分點。
感謝您的字符串查找提示。永遠喜歡聽到std解決方案!
erase()函數呢?如果您知道要在字符串中拆分的位置,則可以使用erase()"提取"字符串中的字段。
std::string date("01/02/2019");
std::string day(date);
std::string month(date);
std::string year(date);
day.erase(2, string::npos); //"01"
month.erase(0, 3).erase(2); //"02"
year.erase(0,6); //"2019"
您是否有理由不想將string轉換為字符數組(char*)?調用.c_str()相當容易。您還可以使用循環和.find()函數。
弦類
字符串.find()
字符串.c_str()
總結
以上是生活随笔為你收集整理的c语言字符串定界符,关于c ++:按字符分割字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iterm php,iTerm2笔记
- 下一篇: c语言编程被当作病毒,为什么这个微不足道