Reputation: 89
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!
Upvotes: 2
Views: 601
Reputation: 33904
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!
Upvotes: 7
Reputation: 4454
you need to fix capitalize(char *str)
to check all characters of the string,not just single character.A use of pointer can save you from including <string.h>
to use strlen()
function,like the following:
#include <stdio.h>
void capitalize(char *str)
{
char *p = str;
while(*p++) {
if (*p >= 97 && *p <= 122) {
*p -= 32;
}
}
}
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);
}
Upvotes: 0
Reputation: 2103
Try this:
void capitalize(char *str)
{
int i = 0;
while (str[i] != '\0')
{
if (str[i] >= 97 && str[i] <= 122) {
str[i] = str[i] - 32;
}
i++;
}
}
Upvotes: 1
Reputation: 53016
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.
Upvotes: 3