0

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

  • 立场0
  • 展台1
  • 展台2
  • 展位3
  • 展位4
  • ...
  • 站台10
  • 站台11
  • 运行0
  • 运行1
  • 运行2

等等

如果没有后面的数字,我如何得到字符串是什么?例如,将“stand10”更改为“stand”的功能

4

5 回答 5

4

只是为了展示另一种方式,反向迭代器:

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());
于 2009-02-11T19:20:50.447 回答
4

string::find_last_not_of ("0123456789") 然后 是string::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”,那么您永远无法获得正确的基本名称。我假设你已经意识到了这一点。

还是我错过了什么?只要基本名称在后缀数字之前的末尾不能有数字,它就可以正常工作。

于 2009-02-11T19:21:50.413 回答
1

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.
}
于 2009-02-11T19:23:09.880 回答
1

只是为了完成它,一个带有 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]+$"), "");
于 2009-02-11T19:45:09.327 回答
0

又快又脏又不太优雅:

for (int i = str.GetLength()-1; i >= 0; i--)
    {
    if (!isdigit(str.GetAt(i)) break;

    str.SetAt(i,'\0');
    }
于 2009-02-11T19:18:49.970 回答