简体   繁体   中英

string manipulation in c++

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

1)

std::transform(str.begin(), str.end(), str.begin(), ::tolower);

2)

str = str.substr(0, str.find(";"));

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM