C Function to Convert String to Lowercase: Implementation and Explanation
This function, void Word(int n, char *word), converts a given string to lowercase. It accomplishes this by dynamically allocating memory using malloc, iterating through the string, converting each character to lowercase, and then printing the result.
void Word(int n, char *word) {
void *cat;
cat = malloc((sizeof(char) * n) + 1);
char *initialword = word;
int i;
for (i = 0; i < n; i++) {
*((char*)cat + i) = tolower(*word);
word++;
}
*((char*)cat + i) = '\0';
word = initialword;
printf("%s\n", (char*)cat);
free(cat);
}
Explanation:
-
Memory Allocation:
cat = malloc((sizeof(char) * n) + 1);allocates memory for a string that can holdncharacters plus a null terminator ('\0').
-
Storing Original Word:
char *initialword = word;creates a copy of the original word pointer to be used later.
-
Iterating and Converting:
- The
forloop iteratesntimes, processing each character in the input string. - Inside the loop,
*((char*)cat + i) = tolower(*word);converts the current character to lowercase usingtolowerand stores it in the allocated memory pointed to bycat. word++;increments thewordpointer to move to the next character in the input string.
- The
-
Adding Null Terminator:
*((char*)cat + i) = '\0';appends a null terminator to the end of the lowercase string, making it a valid C string.
-
Printing and Releasing:
word = initialword;resets thewordpointer back to the beginning of the original word for potential further use.printf("%s\n", (char*)cat);prints the lowercase string to the console.free(cat);releases the dynamically allocated memory to prevent memory leaks.
This function provides a clear example of string manipulation, memory management, and lowercase conversion in C. It demonstrates how to use pointers, loops, and standard library functions effectively to perform these operations.
原文地址: https://www.cveoy.top/t/topic/owFy 著作权归作者所有。请勿转载和采集!