Sponsored
Sponsored
This approach involves iterating through each name in the list, transforming the name so that the first letter is uppercase and the rest are lowercase. This is a common string manipulation problem that can be solved using built-in string functions in most programming languages.
Time Complexity: O(n) for each name, where n is the length of the name.
Space Complexity: O(1) since we modify the names in place.
1#include <stdio.h>
2#include <ctype.h>
3#include <string.h>
4
5void formatName(char *name) {
6 if (strlen(name) == 0) return;
7 name[0] = toupper(name[0]);
8 for (int i = 1; name[i] != '\0'; i++) {
9 name[i] = tolower(name[i]);
10 }
11}
12
13int main() {
14 // Example usage
15 char names[][20] = {"aLice", "bOB"};
16 int user_ids[] = {1, 2};
17 int n = sizeof(user_ids) / sizeof(user_ids[0]);
18
19 printf("+---------+-------+\n");
20 printf("| user_id | name |\n");
21 printf("+---------+-------+\n");
22 for (int i = 0; i < n; i++) {
23 formatName(names[i]);
24 printf("| %d | %s |\n", user_ids[i], names[i]);
25 }
26 printf("+---------+-------+\n");
27
28 return 0;
29}
In C, we use the toupper
and tolower
functions from ctype.h
to modify the casing of each character in the string. The first character is capitalized, while the rest are converted to lowercase.
This approach applies regular expressions to locate patterns that match the criteria and replace them with the desired format. This leverages the pattern matching capability of regex to achieve the transformation in fewer lines of code.
Time Complexity: O(n) for each name due to regex matching and replacement, where n is the length of the name.
Space Complexity: O(n) for storing the modified strings.
1import re
2
3def format_names(users
In this Python solution, the regex (\w)(\w*)
captures the first character and the remainder of the string separately. The lambda function then applies the uppercase and lowercase transformations in one substitution step.