如何检查字符串是否以.txt结尾 [英] How to check if string ends with .txt

查看:93
本文介绍了如何检查字符串是否以.txt结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习基本的C ++,现在我已经从用户那里得到了一个字符串,我想检查他们是否键入了整个文件名(包括.txt)。我有字符串,但是如何检查字符串是否以 .txt结尾?

I am learning basic C++, and right now I have gotten a string from a user and I want to check if they typed the entire file name (including .txt) or not. I have the string, but how can I check if the string ends with ".txt" ?

string fileName;

cout << "Enter filename: \n";
cin >> fileName;

string txt = fileName.Right(4);

Right(int)方法仅适用CString,因此上面的代码不起作用。如果可能,我想使用常规字符串。有任何想法吗?

The Right(int) method only works with CString, so the above code does not work. I want to use a regular string, if possible. Any ideas?

推荐答案

不幸的是,此有用的函数不在标准库中。

Unfortunately this useful function is not in the standard library. It is easy to write.

bool has_suffix(const std::string &str, const std::string &suffix)
{
    return str.size() >= suffix.size() &&
           str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}

这篇关于如何检查字符串是否以.txt结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆