Caps Lock Strings

Nov 20, 2013 at 5:37pm
Is there anyway you can switch the caps lock to fix the text in the string? I've came up with something here, but are there any hints that could help me out?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream> 
#include<string> 
using namespace std; 
int main( ) 
{ 
	string s ("cAPS lOCK iS cURRENTLY oN!");
	 
	while (s.find("upper-case") != string::npos)
		s.replace(s.find("upper-case"), 3, "lower-case");
	while (s.find("lower-case") != string::npos)
		s.replace(s.find("lower-case"), 3, "upper-case");

	cout << s << endl;
		
	return 0;
}
Last edited on Nov 21, 2013 at 2:52am
Nov 20, 2013 at 6:26pm
There is no function to find and change an entire string to upper or lower case. But there is a function to test and change individual characters.

 
#include <cctype> 
1
2
3
4
if (isupper( c ))
{
	c = tolower( c );
}
1
2
3
4
if (islower( c )) 
{
	c = toupper( c );
}

In this code, c is the character you are changing (so it will be a reference to an element in your string, like s[3] or s[n].

Take care to notice that once you change a character's case that you not change it back with the next if statement.

You can't find "upper-case" in your string, since it does not have the text "upper-case" in it:

    "This is not upper-case."    (found at index 12)

    "I yam what I yam."          (not found)

Hope this helps.
Last edited on Nov 20, 2013 at 6:26pm
Nov 20, 2013 at 6:31pm
@firstlast

There is also this way..

1
2
3
4
5
6
7
8
9
10
11
12
string s ("cAPS lOCK iS cURRENTLY oN!");
	 
	int len = s.length();
	for(int x = 0;x < len; x++)
	{
		if (s[x] >= 97 && s[x] <=122)
			s[x] = toupper(s[x]);
		else
		if (s[x] >= 65 && s[x] <=90)
			s[x] = tolower(s[x]);
	}
cout << s << endl;
Nov 20, 2013 at 7:49pm
Use' toupper' and 'tolower' in the <ctype.h> header file.

http://www.cplusplus.com/reference/cctype/toupper/
Nov 20, 2013 at 7:50pm
LOL, another complete solution. Why bother using toupper() and tolower() if you aren't going to use isupper() and islower() also?
Nov 20, 2013 at 8:12pm
I'm not going to give someone the complete answer.

"Give a man a fish and you have fed him for a day, teach a man to fish and you have fed him for a lifetime."
Nov 20, 2013 at 9:30pm
@Parasin
See the post above yours.
Topic archived. No new replies allowed.