在编写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] 删除。
我来说两句