首页 > 解决方案 > 如何根据字符拆分字符串

问题描述

我可以从以下行获取子字符串

string filename = C:\Shaders\Test\Model\source\scene.fbx"
filename.substr( 0 , filename.find_last_of('\') );

这将是结果

C:\Shaders\Test\Model\source

现在,如果我想获取从最后一个“\”到字符串末尾的子字符串

scene.fbx 

我正在尝试这条线。

filename.substr(filename.find_last_of('/'), filename.size() )

但我要崩溃了。

标签: c++

解决方案


#include <iostream>
using namespace std;
int main() {
    string s = "C:\\Shaders\\Test\\Model\\source\\scene.fbx";
    cout<<s<<endl<<s.substr(s.find_last_of('\\')+1, s.length())<<endl;
    // As @David suggested in comments, you can omit `s.length()`
    cout<<s.substr(s.find_last_of('\\')+1);
}

输出

C:\Shaders\Test\Model\source\scene.fbx
scene.fbx
scene.fbx

推荐阅读