[英]check what number a string ends with in C++
在C ++ MD2文件加載器中,我有很多框架,每個框架的名稱都以數字結尾,例如
等等
如何獲得沒有數字的字符串呢? 例如,將“ stand10”更改為“ stand”的函數
只是為了顯示另一種方式,反向迭代器:
string::reverse_iterator rit = str.rbegin();
while(isdigit(*rit)) ++rit;
std::string new_str(str.begin(), rit.base());
如果您擁有boost :: bind,可以使您的生活更輕松
std::string new_str(str.begin(),
std::find_if(str.rbegin(), str.rend(),
!boost::bind(::isdigit, _1)).base());
字符串:: find_last_not_of (“ 0123456789”),然后字符串:: substr()
給出最后一個非數字/數字的位置。 只要取所有前面的字符,那就是基本名稱。
遞增1以在字符串的末尾獲得數字序列的開始。
注意:請勿進行錯誤檢查或其他測試。
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string test = "hellothere4";
size_t last_char_pos = test.find_last_not_of("0123456789");
string base = test.substr(0, last_char_pos + 1);
編輯
當您的“基本名稱”以數字結尾時,所有解決方案都存在問題。
例如,如果基本字符串是“ base1”,那么您將永遠無法獲得正確的基本名稱。 我認為您已經意識到這一點。
還是我錯過了什么? 只要基本名稱的末尾編號前不能有數字,它就可以正常工作。
C風格的實現方式:
從左邊開始,逐個字符地迭代字符串。 讀取數字時,請停止並將其標記為字符串的結尾。
char *curChar = myString; // Temporary for quicker iteration.
while(*curChar != '\0') { // Loop through all characters in the string.
if(isdigit(*curChar)) { // Is the current character a digit?
*curChar = '\0'; // End the string.
break; // No need to loop any more.
}
++curChar; // Move onto the next character.
}
為了完成它,使用find_first_of:
string new_string = str.substr(0, str.find_first_of("0123456789"));
僅一行:)
另外,對於這些事情,我喜歡使用正則表達式(盡管這種情況非常簡單):
string new_string = boost::regex_replace(str, boost::regex("[0-9]+$"), "");
快速又臟又不太優雅:
for (int i = str.GetLength()-1; i >= 0; i--)
{
if (!isdigit(str.GetAt(i)) break;
str.SetAt(i,'\0');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.