使用const std :: string指针作为函数参数

凯慕尔

在编写Java多年之后,我想再次更深入地研究C ++。

尽管我认为我可以处理,但我不知道是否以“最新技术”处理它。

目前,我尝试了解如何处理作为常量指针传递给方法的参数的std :: strings。

以我的理解,我想对指针的内容(实际的字符串)执行的任何字符串操作都是不可能的,因为它是const。

我有一种方法应该将给定的字符串转换为小写,并且为了使给定的字符串可编辑,我做了大量的工作(我相信)。看一看:

class Util
{
  public:
  static std::string toLower(const std::string& word)
  {
    // in order to make a modifiable string from the const parameter
    // copy into char array and then instantiate new sdt::string
    int length = word.length();
    char workingBuffer[length];
    word.copy(workingBuffer, length, 0);

    // create modifiable string
    std::string str(workingBuffer, length);

    std::cout << str << std::endl;

    // string to lower case (include <algorithm> for this!!!!)
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);

    std::cout << str << std::endl;

    return str;
  }
};

尤其是在第一部分中,我使用char缓冲区将给定的字符串复制到可修改的字符串中,这使我很烦。有更好的方法来实现这一点吗?

问候,迈克

莱尼克

您应该替换所有这些:

// in order to make a modifiable string from the const parameter
// copy into char array and then instantiate new sdt::string
int length = word.length();
char workingBuffer[length];
word.copy(workingBuffer, length, 0);

// create modifiable string
std::string str(workingBuffer, length);

简单的说:

std::string str(word);

它应该可以正常工作=)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

const指针作为std :: bind参数

智能指针作为使用 std::function, std::bind 的函数的参数

使用std :: ostream作为打印函数的参数

使用 std:array 作为函数的参数

使用指针作为函数的参数

指向const的指针作为函数参数

const指针作为函数参数的含义

如何使用inst const char *作为std :: string内容

const std :: string&s = nullptr如何作为可选参数

我可以使用std :: string * argv作为主要函数参数吗?

使用删除的函数'std :: thread :: thread(const std :: thread&)'

如何使用std :: array构造函数参数C ++列表初始化const std :: array成员

使用引用指针作为函数参数的危险

使用值代替指针作为函数参数

C const 指向 const struct 数组的指针作为函数参数

C ++“错误:将'const std :: map <int,std :: basic_string <char>>'作为...的'this'参数传递”

如何使用函数签名的typedef作为std :: function的类型参数?

gdb调用函数-如何使用std :: cout作为参数?

使用std :: get作为std :: transform的参数

如何使用std:string参数迭代可变参数函数?

使用 auto 添加 const 的 std::function 参数类型的类型推导

const指针作为参数传递给constexpr函数

没有可变参数调用std :: forward(const std :: string&)的匹配函数

const函数指针类型作为模板参数的“无效使用不完整类型”

如何干净使用:const char *和std :: string?

什么时候应该使用std :: string / std :: string_view作为参数/返回类型

使用函数指针作为模板函数类型参数?

将const std :: string&作为参数传递的日子已经过去了吗?

不能从const char *推导std :: basic_string作为功能模板的参数