繁体   English   中英

检查字符串以C ++结尾的数字

[英]check what number a string ends with in C++

在C ++ MD2文件加载器中,我有很多框架,每个框架的名称都以数字结尾,例如

  • 展位0
  • Stand1
  • stand2
  • stand3
  • stand4
  • ...
  • 展位10
  • Stand11
  • 运行0
  • 运行1
  • 运行2

等等

如何获得没有数字的字符串呢? 例如,将“ 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.

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