【问题标题】:How switch char* on std::string in my implementation of func? [closed]在我的 func 实现中如何在 std::string 上切换 char*? [关闭]
【发布时间】:2020-04-28 07:08:14
【问题描述】:

如何将我的函数从 const char* 转换为字符串?我需要它没有模板。只需在 pattern_founder(std::string, std::string) 上重建我的函数 pattern_founder(const char*, const char*)。我试图用迭代器来做,但是出了点问题。谢谢。

 static bool pattern_founder(const char* file_path_ptr, const char* pattern) noexcept
    {
        const char* supp_file_path_ptr = nullptr;
        const char* supp_pattern = nullptr;
        while (true) 
            if (*pattern == '*') {
                supp_file_path_ptr = file_path_ptr;
                supp_pattern = ++pattern;
            }
            else if (!*file_path_ptr)
                return !*pattern;
            else if (*file_path_ptr == *pattern || *pattern == '?') {
                ++file_path_ptr;
                ++pattern;
            }
            else if (supp_file_path_ptr) {
                file_path_ptr = ++supp_file_path_ptr;
                pattern = supp_pattern;
            }
            else 
                return false;
    }

【问题讨论】:

  • 您能描述一下代码的用途吗?
  • 请向我们展示您的尝试并解释出了什么问题,我们将帮助您解决问题。但 SO 不是免费的代码编写服务。
  • @JasperKent,好的。这段代码比较两个 C 风格的字符串,并告诉我们在 file_path_ptr 中是否有模式。模式是带有特殊小丑的文件名或文件路径。现在,我编写程序,就像您在 Windows 上的资源管理器中看到的那样,您放置一些行,例如“hello.cpp”,prohramm 比较所有变体并为您提供可能的选项。附:对不起我的英语:#

标签: c++ c++11 visual-c++ c++14 c++17


【解决方案1】:

简单的解决方案是添加这个重载:

static bool pattern_founder(const std::string& file_path, const std::string& pattern) noexcept
{
   return pattern_founder(file_path.c_str(), pattern.c_str());   
}

如果您只想拥有std::string 版本:

static bool pattern_founder(const std::string& file_path, const std::string& pattern_str) noexcept
{
    const char* file_path_ptr = file_path.c_str();
    const char* pattern = pattern_str.c_str();
    // Paste your existing code here.
}

【讨论】:

  • 我现在拥有的第一个变体,但这不是我想要的。第二个变体不适用于我的代码。
  • “没用”是什么意思?如果您现有的代码有效,那么这不会出错。 (它与第一个完全相同,但 c_str()s 在函数内部移动。)
【解决方案2】:

更改此设置的简单方法是将函数参数更改为const std::string 并使用声明变量启动函数,这些变量只是原始字符串的 c 字符串,您可以在其上使用您已经编写的代码.可以通过s.c_str()得到字符串s的C字符串

要使用字符串,您必须#include <string>。您可以通过以下方式将char* 转换为string

char *cStr = "C++";
std::string Str = std::string(cStr);

有了这个,你可以将你的参数转换成一个字符串。另一种方法是将参数类型从const char* 更改为std::string。然后你必须调整你的代码,例如要检查模式的第一个字符是否是星号,可以检查pattern[0] == '*'

您可以在 nullptr 中为其分配一个空字符串并测试该字符串是否为空。

我不知道你想做什么,但你也可以为你在字符串中的哪个字符保留一个索引作为一个单独的整数。

【讨论】:

  • 这行不通。你甚至没有看代码。
猜你喜欢
  • 2016-09-12
  • 2016-06-10
  • 1970-01-01
  • 2010-10-22
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多