Skip to main content

search_and_replace — Find and Replace Character

Allowed functions: write, exit

Write a program that takes 3 arguments, the first argument is a string in which to replace a letter (2nd argument) by another one (3rd argument).

If the number of arguments is not 3, just display a newline. If the second argument is not contained in the first one (the string) then the program simply rewrites the string followed by a newline.

Examples

$>./search_and_replace "Papache est un sabre" "a" "o"
Popoche est un sobre
$>./search_and_replace "zaz" "art" "zul" | cat -e
$
$>./search_and_replace "zaz" "r" "u" | cat -e
zaz$
$>./search_and_replace "ZoZ eT Dovid oiME le METol." "o" "a" | cat -e
ZaZ eT David aiME le METal.$

Solution

Download search_and_replace.c
#include <unistd.h>

int main(int c, char **v) {

if (c != 4 || v[2][1] || v[3][1]) {

write(1, "\n", 1);
return 0;
}

char *str = v[1];
char r = v[2][0];
char w = v[3][0];

while (*str) {
if (*str == r)
*str = w;

write(1, str, 1);
str++;
}
write(1, "\n", 1);

return 0;
}

How It Works

Goal: Replace every occurrence of a specific character in a string with another character.

Approach: Validate that exactly 3 arguments are given and that the search/replace args are single characters, then iterate through the string swapping matches.

Step by step:

  1. Check that there are exactly 4 arguments (program name + 3) and that the 2nd and 3rd arguments are single characters (i.e., v[2][1] and v[3][1] are '\0'). If not, print a newline and exit.
  2. Store the search character r and replacement character w.
  3. Loop through the string: if the current character equals r, replace it with w.
  4. Write each character to stdout, then print a trailing newline.

Key concept: Argument validation and character comparison — checking argument count and ensuring single-character inputs before performing a simple find-and-replace pass.