Hi this code I created capitalizes lower case letters. strcpy manages to copy the value of string to stringTwo, however I was wondering why strcpy changes the value of string as well if I just used it as a parameter. Thanks
#include <stdio.h>
#include <string.h>
char *capitalize(char *str) {
int i;
for (i = 0; i < strlen(str); i++) {
if (str[i] >= 97 && str[i] <= 122) {
str[i] -= 32;
}
}
return str;
}
int main() {
char string[21];
char stringTwo[21];
printf("Enter string: ");
scanf("%20s", string);
strcpy(stringTwo, capitalize(string));
printf("\n%s\ncapitalized: %s", string, stringTwo);
return 0;
}
The problem is that the capitalize
function converts all letters to upper-case in place. That is, the string you pass as argument will be the one being converted.
If you don't want the original string to be modified, you need to do it in two steps:
strcpy(stringTwo, string); // First copy the original string
capitalize(stringTwo); // Then make all letters upper-case in the copy
or
capitalize(strcpy(stringTwo, string));
if it needs to be one step... Ok, looks ugly...