0

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;
}
jason96
  • 57
  • 5
  • 1
    `strcpy()` does _not_ change the value of `string`, but `capitalize()` does! – Ctx Jan 31 '20 at 09:35
  • 4
    Please don't use [magic numbers](https://en.wikipedia.org/wiki/Magic_number_(programming)), or encoding-specific code like this. All you really need is the [toupper](https://en.cppreference.com/w/c/string/byte/toupper) function, you don't even need to check if the character is lower-case or upper-case (or indeed a letter) first. – Some programmer dude Jan 31 '20 at 09:37
  • Why are you using the values 97 and 122? Use 'a' and 'z' instead? Makes the code more readable – Ed Heal Jan 31 '20 at 10:20
  • 1
    and don't call `strlen()` inside the for loop as the length will be unnecessarily calculated again and again – phuclv Jan 31 '20 at 10:25

2 Answers2

2

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
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    or `capitalize(strcpy(stringTwo, string));` if it needs to be one step... Ok, looks ugly... – Ctx Jan 31 '20 at 09:43
0

Because you are changing the original one ( which is "string") and copying it to the new one (which is stringTwo).

If you have a chance for using a debugger, then you will see that in the first place you are changing the "string".

Edit: Or you can try this if you prefer: I changed the code a little bit.

    char *capitalize(char *str,char *str2) {
    strcpy(str2, str);
    int i;
    for (i = 0; i < strlen(str2); i++) {

        if (str2[i] >= 97 && str2[i] <= 122) {

            str2[i] -= 32;

        }

    }

    return str2;
}

With this little change in your function, you are doing all the work in the function. You just type the capitalize(string,stringTwo);and this will do what you've wanted.

mkde
  • 17
  • 1
  • 6