去哪儿网 笔试编程题

filename extension

题目描述

Please create a function to extract the filename extension from the given path,return the extracted filename extension or null if none.

输入描述:

输入数据为一个文件路径

输出描述:

对于每个测试实例,要求输出对应的filename extension

示例1

输入

Abc/file.txt

输出

txt

思路:输出文件扩展名。主要是找到 . 的位置index,从index+1开始到结尾截取子串,则为扩展名

#include<iostream>
#include<string>
using namespace std;

int main(){
    string str;
    cin >> str;
    int index = str.find('.'); //找到返回下标值,没找到返回-1
    if(index == -1)
        cout << "null" << endl;
    else{
        //index不为-1,表示找到了 . ,则截取 . 以后的子串
        string temp = str.substr(index+1, str.size()-index -1);
        cout << temp << endl;
    }
    return 0;
}

点赞