So, for an assignment, I had to finish a code meant to capitalize a string.
What I tried was this:
#include <stdio.h>
void capitalize(char *str)
{
int i = 0;
if (str[i] >= 97 && str[i] <= 122)
{
str[i] = str[i] - 32;
}
else
{
i++;
}
}
void strCopy(char *str2, char *str1)
{
while (*str2)
{
*str1 = *str2;
str2++;
str1++;
}
*str1 = '\0';
}
int main(int argc, char **argv)
{
char string1[100] = "This is a really long string!";
char string2[100];
strCopy(string1,string2);
capitalize(string2);
printf("The original string is \"%s\"\n", string1);
printf("The capitalized string is \"%s\"\n", string2);
}
However, when I tried running the code it returned:
The original string is "This is a really long string!"
The capitalized string is "This is a really long string!"
strcopy does not seem to be the issue, as it copies the string1 correctly to string2.
I don't understand why capitalize is not working, as it seems like it should be going through letter by letter and changing it to uppercase, if the letter falls within the ascii code for a lowercase letter.
I would greatly appreciate someone helping to point out where the error is.
Thanks in advance!
The problem is that your capitilize function doesn't have a loop. You only ever capitalize the first letter of your string.
You are on the right track but what you are looking for is this:
for (int i = 0; str[i] != '\0'; ++i) { // Here we check for the end condition of a string.
// ie. Has the Null termination been reached?
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - ('a' - 'A');
}
}
Here is a live demo for you to play with!
Your capitalize() function only runs for one character. Try like this
for (int i = 0 ; str[i] != '\0' ; ++i) {
if (str[i] >= 97 && str[i] <= 122)
str[i] = str[i] - 32;
}
perform the operation on every character until the '\0' is found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With