Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

StrProper in C++

Status
Not open for further replies.

DarkAlchemist

Programmer
Jan 19, 2004
18
US
Is there a function like Strlwr and StrUpper but for making a proper case for us C++ users? If so where is it? :)

Thanks.
 
If using C-style char* or char[] strings then a loop and tolower() or toupper() is all you need.
If using C++ style std::string objects then I have done this by using the algorithm std::transform() and passing a pointer to tolower or toupper to that algorithm.
Look those functions up in your help files for usage.
 
yes,
strupr, strlvr, wcsupr, wcslvr

Ion Filipski
1c.bmp
 
How well would this handle BLAH blah vi? Blah Blah VI is what I would expect but the true proper would be Blah blah VI.
 
Oh if that is the behaviour you want then I suspect you will have to roll your own implementation. Shouldn't be too hard to write a function object to handle this and again use it with transform and string.
 
void main()
{
std::string myString ("heLlo this is a tEsT VI");
std::string::size_type len = myString.length();
int a = 1;
for (int x = 0; x < len; x++)
{
int c = myString[x];
if (a)
{
c = toupper(c);
a = 0;
}
else
c = tolower(c);
if (c == 0x20)
a++;
myString[x] = (char) c;
}
unsigned int loc = myString.find_last_of(&quot; &quot;);
if (loc != std::string::npos)
{
std::string b = myString.substr(++loc);
std::transform(b.begin(), b.end(), b.begin(), tolower);
if (b == &quot;i&quot; || b == &quot;ii&quot; || b == &quot;iii&quot; || b == &quot;iv&quot; || b == &quot;v&quot; || b == &quot;vi&quot;)
{
for (x = loc; x < len; x++)
myString[x] = toupper(myString[x]);
}
}
std::cout << myString << std::endl;
}

This is what I came up with and was wondering if it could be optimized?
 
Ah, yes the joy of optimizing...

Unless your code is gonna run on a 1Hz machine and/or be called a kazzillion times a second I wouldn't bother with the optimization...

However somthing like checking every char from the end to the front springs to mind. On first encounter of a space (=the last space in the string) do a &quot;to-uppercase&quot; on the string from current pos. Lowercase all chars except the one at pos 0, which you uppercase.
That way each character is checked once and only once (and no sneaky find_last_of either ;-) )


/Per

&quot;It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top