Reputation: 79
I have a string interface (const char* value, uint32_t length) which I need to manipulate.
1) I have to make it all lower case
2) I have to remove all characters found after the ';' semicolon
Can anyone help point me to any C/C++ libraries that can do this? without me having to iterate through the char array.
Thanks in advance
Upvotes: 0
Views: 497
Reputation: 393759
See here: 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';
}
Output:
test case number 1
Upvotes: 2
Reputation: 9260
1)
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
2)
str = str.substr(0, str.find(";"));
Upvotes: 3
Reputation: 10497
I'd suggest you do (2) first as it will potentially give (1) less work to do.
If you're sticking with traditional C functions, you can use strchr()
to find the first ';' and either replace that with '\0' (if the string is mutable) or use pointer arithmetic to copy to another buffer.
You can use tolower()
to convert an ASCII (I'm assuming you're using ASCII) to lowercase but you'll have to iterate through your remaining loop to do this.
For example:
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"
Upvotes: 1