Lesson 10 of 23
cut
The cut Command
cut extracts a specific field from each line of delimited text:
$ printf "alice:30:engineer\nbob:25:designer\n" | cut -d: -f2
30
25
-d: sets the delimiter to :, and -f2 selects the second field. Fields are 1-indexed.
Your Implementation
Write void my_cut(const char *s, char delim, int field) that prints the given field from each line.
The algorithm: for each line, count delimiter occurrences to track which field you are in. When you reach the target field, print its characters.
void my_cut(const char *s, char delim, int field) {
while (*s) {
int cur = 1;
while (*s && *s != '\n') {
if (*s == delim) {
cur++;
} else if (cur == field) {
putchar(*s);
}
s++;
}
putchar('\n');
if (*s == '\n') s++;
}
}
Counting Fields
Each time you encounter the delimiter, move to the next field (cur++). When cur == field, the current character belongs to the target field — print it. Delimiter characters themselves are never printed.
Your Task
Implement my_cut that prints the specified field from each line using the given delimiter.
TCC compiler loading...
Loading...
Click "Run" to execute your code.