string to lowercase

Started by
4 comments, last by jflanglois 18 years ago
I know about char* _strlwr(char*) but what I want is to be able to use this with a string variable, like: string strg; I tried it but it gives me a "cannot convert class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > to char*" error. What can I do?
Advertisement
Try the boost string algorithm library, which will give you this plus a lot of other useful stuff. Or if you want quick and dirty, just do myString = std::tolower(myString) for every element of the string (or perhaps use a std:: algorithm such as for_each).

[Edit: Oops, forgot about std::transform().]

[Edited by - jyk on March 28, 2006 11:14:34 AM]
Edit: See jflanglois post re: using STL's transform function to convert case.

For what it's worth, here are a couple of functions which you may or may not also need in the future:

wsts - converts a std::wstring to std::string (as best it can, of course)
stws - converts a std::string to std::wstring



string wsts(const basic_string<wchar_t> &src_string){	size_t src_len = src_string.length();	if(src_len == 0)		return "";	char *buf = new(std::nothrow) char[src_len + 1];	if(buf == 0)		return "";	wcstombs(buf, src_string.c_str(), src_len);	buf[src_len] = '\0';	string final_string = buf;	if(buf != 0)		delete [] buf;	return final_string;}basic_string<wchar_t> stws(const string &src_string){	size_t src_len = src_string.length();	if(src_len == 0)		return L"";	wchar_t *buf = new(std::nothrow) wchar_t[src_len + 1];	if(buf == 0)		return L"";	mbstowcs(buf, src_string.c_str(), src_len);	buf[src_len] = L'\0';	basic_string<wchar_t> final_string = buf;	if(buf != 0)		delete [] buf;	return final_string;}


[Edited by - taby on March 28, 2006 11:18:55 AM]
I agree with jyk about the Boost String Algorithm library, but if you do not wish to use boost, you can do it almost as easily with the STL:

#include <string>#include <ctype.h>#include <algorithm>int main() {  std::string str = "To LoWeR cAsE";  std::transform( str.begin(), str.end(), str.begin(), tolower );}


jfl.
Quote:Original post by jflanglois
I agree with jyk about the Boost String Algorithm library, but if you do not wish to use boost, you can do it almost as easily with the STL:

#include <string>#include <locale>#include <algorithm>int main() {  std::string str = "To LoWeR cAsE";  std::transform( str.begin(), str.end(), str.begin(), tolower );}


jfl.


Very nice. Thanks for that. :)
Quote:Very nice. Thanks for that. :)

You're welcome. As a side note, I recommend reading SGI's STL reference.

This topic is closed to new replies.

Advertisement