Как проверить, заканчивается ли строка с .txt
Я изучаю базовый С++, и сейчас у меня есть строка от пользователя, и я хочу проверить, набрали ли они все имя файла (включая .txt) или нет. У меня есть строка, но как я могу проверить, заканчивается ли строка с ".txt"?
string fileName;
cout << "Enter filename: \n";
cin >> fileName;
string txt = fileName.Right(4);
Метод Right(int)
работает только с CString, поэтому приведенный выше код не работает. Я хочу использовать регулярную строку, если это возможно. Любые идеи?
Ответы
Ответ 1
К сожалению, эта полезная функция отсутствует в стандартной библиотеке. Легко писать.
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;
}
Ответ 2
Использование boost ends_with предикат:
#include <boost/algorithm/string/predicate.hpp>
if (boost::ends_with(fileName, ".txt")) { /* ... */ }
Ответ 3
У вас уже есть несколько ответов, но я решил добавить еще один:
bool ends_with(std::string const &a, std::string const &b) {
auto len = b.length();
auto pos = a.length() - len;
if (pos < 0)
return false;
auto pos_a = &a[pos];
auto pos_b = &b[0];
while (*pos_a)
if (*pos_a++ != *pos_b++)
return false;
return true;
}
Поскольку вы получили немало ответов, возможно, быстрый тест и резюме результатов будут полезны:
#include <iostream>
#include <string>
#include <vector>
#include <time.h>
#include <iomanip>
bool ends_with(std::string const &a, std::string const &b) {
auto len = b.length();
auto pos = a.length() - len;
if (pos < 0)
return false;
auto pos_a = &a[pos];
auto pos_b = &b[0];
while (*pos_a)
if (*pos_a++ != *pos_b++)
return false;
return true;
}
bool ends_with_string(std::string const& str, std::string const& what) {
return what.size() <= str.size()
&& str.find(what, str.size() - what.size()) != str.npos;
}
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;
}
bool has_suffix2(const std::string &str, const std::string &suffix)
{
bool index = str.find(suffix, str.size() - suffix.size());
return (index != -1);
}
bool isEndsWith(const std::string& pstr, const std::string& substr)
{
int tlen = pstr.length();
int slen = substr.length();
if (slen > tlen)
return false;
const char* tdta = pstr.c_str();
const char* sdta = substr.c_str();
while (slen)
{
if (tdta[tlen] != sdta[slen])
return false;
--slen; --tlen;
}
return true;
}
bool ends_with_6502(const std::string& str, const std::string& end) {
size_t slen = str.size(), elen = end.size();
if (slen <= elen) return false;
while (elen) {
if (str[--slen] != end[--elen]) return false;
}
return true;
}
bool ends_with_rajenpandit(std::string const &file, std::string const &suffix) {
int pos = file.find(suffix);
return (pos != std::string::npos);
}
template <class F>
bool test(std::string const &label, F f) {
static const std::vector<std::pair<std::string, bool>> tests{
{ "this is some text", false },
{ "name.txt.other", false },
{ "name.txt", true }
};
bool result = true;
std::cout << "Testing: " << std::left << std::setw(20) << label;
for (auto const &s : tests)
result &= (f(s.first, ".txt") == s.second);
if (!result) {
std::cout << "Failed\n";
return false;
}
clock_t start = clock();
for (int i = 0; i < 10000000; i++)
for (auto const &s : tests)
result &= (f(s.first, ".txt") == s.second);
clock_t stop = clock();
std::cout << double(stop - start) / CLOCKS_PER_SEC << " Seconds\n";
return result;
}
int main() {
test("Jerry Coffin", ends_with);
test("Dietrich Epp", has_suffix);
test("Dietmar", ends_with_string);
test("Roman", isEndsWith);
test("6502", ends_with_6502);
test("rajenpandit", ends_with_rajenpandit);
}
Результаты с gcc:
Testing: Jerry Coffin 3.416 Seconds
Testing: Dietrich Epp 3.461 Seconds
Testing: Dietmar 3.695 Seconds
Testing: Roman 3.333 Seconds
Testing: 6502 3.304 Seconds
Testing: rajenpandit Failed
Результаты с VС++:
Testing: Jerry Coffin 0.718 Seconds
Testing: Dietrich Epp 0.982 Seconds
Testing: Dietmar 1.087 Seconds
Testing: Roman 0.883 Seconds
Testing: 6502 0.927 Seconds
Testing: rajenpandit Failed
Да, те были запущены на одинаковом аппаратном обеспечении, и да, я запускал их несколько раз и пробовал разные варианты оптимизации с g++, чтобы увидеть, могу ли я получить его, по крайней мере, приблизиться к соответствующему VС++. Я не мог. У меня нет непосредственного объяснения того, почему g++ производит гораздо худший код для этого теста, но я уверен, что он это делает.
Ответ 4
Используйте std::string::substr
if (filename.substr(std::max(4, filename.size())-4) == std::string(".txt")) {
// Your code here
}
Ответ 5
вы можете просто использовать другую строку, чтобы проверить расширение следующим образом:
string fileName;
cout << "Enter filename: \n";
cin >> fileName;
//string txt = fileName.Right(4);
string ext="";
for(int i = fileName.length()-1;i>fileName.length()-5;i--)
{
ext += fileName[i];
}
cout<<ext;
if(ext != "txt.")
cout<<"error\n";
проверка, если равно "txt."
, я начинаю с длины имени файла, поэтому ext
заполняется противоположным образом
Ответ 6
Самый простой подход - это, вероятно, проверить, что строка достаточно длинная, чтобы удерживать ".txt"
вообще и посмотреть, можно ли найти строку в позиции size() - 4
, например:
bool ends_with_string(std::string const& str, std::string const& what) {
return what.size() <= str.size()
&& str.find(what, str.size() - what.size()) != str.npos;
}
Ответ 7
bool has_suffix(const std::string &str, const std::string &suffix)
{
std::size_t index = str.find(suffix, str.size() - suffix.size());
return (index != std::string::npos);
}
Ответ 8
Это то, чего, к сожалению, нет в стандартной библиотеке, и это также несколько раздражает писать. Это моя попытка:
bool ends_with(const std::string& str, const std::string& end) {
size_t slen = str.size(), elen = end.size();
if (slen < elen) return false;
while (elen) {
if (str[--slen] != end[--elen]) return false;
}
return true;
}
Ответ 9
2 варианта, о которых я могу вспомнить:
1) regex - prob overkill для этого, но простые регулярные выражения приятные и читаемые IMHO
2) rbegin - добрый, может быть, я чего-то не хватает, но вот он:
bool ends_with(const string& s, const string& ending)
{
return (s.size()>=ending.size()) && equal(ending.rbegin(), ending.rend(), s.rbegin());
}
http://coliru.stacked-crooked.com/a/4de3eafed3bff6e3
Ответ 10
Вот "полностью самозаписываемое" решение:
bool isEndsWith(const std::string& pstr, const std::string& substr) const
{
int tlen = pstr.length();
int slen = substr.length();
if(slen > tlen)
return false;
const char* tdta = pstr.c_str();
const char* sdta = substr.c_str();
while(slen)
{
if(tdta[tlen] != sdta[slen])
return false;
--slen; --tlen;
}
return true;
}