Greetings,
Thinking on the same line, lets walk along the string. Better yet, lets use a while loop to do so. By creating a seperate function to modify the string would probably be beneficial in this case. If we send the string to another function, we can treat it like a pointer allowing us to take the advantage of using the
indirection or
dereferencing operator *.
Pointers are not hard to understand, and I have written two tutorials on them. You can find them here:
Pointers (Part I): An Introduction
Pointers (Part II): Pointers In Application
Back on topic, we can create a function called checkString() if we wanted to. We will need to somehow retreive our string so lets make checkString() take one argument.
Let's look at what we can try:
#include <iostream>
#include <ctype.h>
using namespace std;
void checkString(char *str) {
char lower[] = "abcdefghijklmnopqrstuvwxyz";
while (*str) {
// If not in the alphabet, increment and start again
if (!isalpha(*str)) {
str++;
continue;
}
// If any lower letter was found in *str
if (strchr(lower, *str)) {
// Change to upper
*str = toupper(*str);
}
// Increment location
str++;
}
} Whoa! Lots to digest. Alright, lets start at the beginning. We take a single argument called
str.
After this we create a local variable called lower. This contains all of our letters in the alphabet that are lower case.
Next we check if the current location of our pointer is a letter in the alphabet, though if not the loop continues and increments our array by one. If a letter is found using strchr() then we send it to upper case. The strchr() trick is quite neat. We know that strchr() checks for a letter in a string. Our letter is *
str and our string is
lower.
Next we increment the location of
str. That is the only way to make the loop continue, as our while loop just checks if it exists and is not NULL.
Edit: Forgot to add that isalpha() is a ctype function. That is why we include ctype.h
All this does is tells us if the current location of our string is apart of the alphabet or not.
Just for an example, we could call on main() as the following:
int main (void) {
char sentence[25] = "Hello There";
checkString(sentence);
cout << sentence << endl;
return 0;
} If you have further questions, please feel free to ask.
-
Stack
Overflow