Lesson 12 of 23
tr
The tr Command
tr (translate) maps every character in from to the corresponding character in to:
$ echo "hello" | tr 'aeiou' 'AEIOU'
hEllO
$ echo "hello world" | tr 'a-z' 'A-Z'
HELLO WORLD
Each character in from[i] is replaced by to[i]. Characters not in from pass through unchanged.
Your Implementation
Write void my_tr(const char *s, const char *from, const char *to) that translates characters.
For each character in s, search for it in from. If found at position i, print to[i]. Otherwise print the character as-is.
void my_tr(const char *s, const char *from, const char *to) {
while (*s) {
char c = *s;
for (int i = 0; from[i] && to[i]; i++) {
if (c == from[i]) { c = to[i]; break; }
}
putchar(c);
s++;
}
}
Why a Loop Instead of a Ternary?
The single-char version used *s == from ? to : *s. With a string mapping you need to search the full from table for a match. The inner for loop does this — it walks both from and to together, stopping when it finds a match or reaches the end.
Your Task
Implement my_tr that translates every character in s according to the from → to mapping.
TCC compiler loading...
Loading...
Click "Run" to execute your code.