Hello,
This might be better explained with my code below. if you are return a *string or a string[].
The idea is to convert the whole string to upper case without depending on any other libraries.
However, if the user passes in a *string or a string[] would it depend on how I return them to the calling function. This is what I am experimenting with here.
I thought if I new what was being used, I could return based on that.
Any corrections that are needed for my code, please advise.
Many thanks,
This might be better explained with my code below. if you are return a *string or a string[].
The idea is to convert the whole string to upper case without depending on any other libraries.
However, if the user passes in a *string or a string[] would it depend on how I return them to the calling function. This is what I am experimenting with here.
I thought if I new what was being used, I could return based on that.
Any corrections that are needed for my code, please advise.
Many thanks,
Code:
char* ToUpper(char *str, const int length)
{
char *reset = str; //For reseting the pointer to point to the ordinal address.
int character;
char *destString = malloc(length * sizeof(char));
int i = 0;
//Check to see if actual memory was allocated.
if(destString == NULL)
{
return NULL;
}
//Copy the contents to the array.
//A pointer to an array cannot be modified
while(*str)
{
destString[i] = *str++;
i++;
}
destString[i] = '\0'; //Terminate the end of the string.
str = reset; //Reset the pointer to point to the first character in the character array.
i = 0;
while(*str)
{
//Get the character and subtract 32 to make it upper case.
//Filter for only lower case characters.
if(*str >= 97 && *str <= 122)
{
//Get the character that is lower case and subtrack 32 to make it a upper case character
character = (int) destString[i];
character -= 32;
//Assign the upper case character back into its position in the array.
destString[i] = (char) character;
}
str++;
i++;
}
destString[i] = '\0';
//Point the character array about to the first character in the array.
//str = reset;
str = destString;
return destString;
}
int main(int argc, char** argv)
{
char *string1 = "Hello how are you today?";
char string2[] = "Hello how are you today?";
string1 = ToUpper(string1, strlen(string1));
printf("string1: %s\n", string1);
string2[0] = ToUpper(string2, strlen(string2));
printf("string2: %s\n", string2);
return 0;
}