我有一个字符串接口(const char *值,uint32_t长度),我需要操作。C++中的字符串操作
1)I必须使它所有小写
2)I必须删除后的所有字符的“;”分号
任何人都可以帮助我指出任何可以做到这一点的C/C++库吗?没有我必须遍历char数组。
在此先感谢
我有一个字符串接口(const char *值,uint32_t长度),我需要操作。C++中的字符串操作
1)I必须使它所有小写
2)I必须删除后的所有字符的“;”分号
任何人都可以帮助我指出任何可以做到这一点的C/C++库吗?没有我必须遍历char数组。
在此先感谢
1)
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
2)
str = str.substr(0, str.find(";"));
我建议你(2)第一,因为这将可能给(1)减少工作做。
如果您坚持使用传统的C函数,您可以使用strchr()
来查找第一个';'并用'\ 0'(如果该字符串是可变的)替换它,或者使用指针算术复制到另一个缓冲区。
您可以使用tolower()
将ASCII(我假设您使用ASCII)转换为小写字母,但您必须遍历剩余的循环才能执行此操作。
例如:
const char* str = "HELLO;WORLD";
// Make a mutable string - you might not need to do this
int strLen = strlen(str);
char mStr[ strLen + 1];
strncpy(mStr, str, strLen);
cout << mStr << endl; // Prints "HELLO;WORLD"
// Get rid of the ';' onwards.
char* e = strchr(mStr, ';');
*e = '\0';
cout << mStr << endl; // Prints "HELLO"
for (char* p = mStr; p != e; *p = tolower(*p), p++);
cout << mStr << endl; // Prints "hello"
谢谢,这些都是我需要的完美库。 – CodeBlocks 2012-07-13 10:28:06
@CodeBlocks:谢谢,但除非你有很好的理由坚持旧的C风格的功能,否则我强烈建议你给AljoshaBre的回答一下。正如你所看到的,从C++的角度来看,它更加优雅。 – 2012-07-13 10:38:44
在这里看到:http://ideone.com/fwJx5:
#include <string>
#include <iostream>
#include <algorithm>
std::string interface(const char* value, uint32_t length)
{
std::string s(value, length);
std::transform(s.begin(), s.end(), s.begin(), [] (char ch) { return std::tolower(ch); });
return s.substr(0, s.find(";"));
}
int main()
{
std::cout << interface("Test Case Number 1; ignored text", 32) << '\n';
}
输出:
test case number 1
你的意思是 “没有明确地迭代”?因为,不管你使用什么方法/库,它必须通过所有的角色! – go4sri 2012-07-13 10:18:05
助推是你的朋友! – 2012-07-13 10:18:17
我想,OP的意思是:“我不想自己写这个循环。”我知道,我是一个心灵读者。 – 2012-07-13 10:19:23