{ }codelper
replacing textP0055

Find and replace all

The first line gives a text, the second line a word a to find, and the third line a word b to put in its place.
Print the text with every a replaced by b.
Search the original text from the left; a part that has been replaced is not searched again.
So replacing "aa" with "b" in "aaa" gives "ba", and replacing "a" with "aa" in "banana" gives "baanaanaa".
Symbols in a and b (.
$ ( \ and so on) have no special meaning; they stand for themselves.
If a does not occur, print the text unchanged.

Input
text: printable ASCII (32 to 126) including spaces (no leading or trailing spaces), length 1 to 1,000.
a and b: ASCII without spaces, length 1 to 10
Output
one line, the replaced text
Example 1 · stdin
I like cats. cats are cute.
cats
dogs
stdout
I like dogs. dogs are cute.
Example 2 · stdin
a.b.c
.
$$
stdout
a$$b$$c
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Functions that replace "every occurrence, literally": Python text.replace(a, b), Java text.replace(a, b), C# text.Replace(a, b) (ordinal), Craykon text.Replace(a, b).
JS and Java hold the traps.
(1) JS/TS text.replace("cats", "dogs") with a string pattern replaces only the first match.
(2) replaceAll(a, b) replaces them all, but reads $& (the match) and $$ (one dollar) in the replacement as special patterns, so "$$" shrinks to "$".
For a literal replacement use text.split(a).join(b) or pass a function () => b.
(3) Java replaceAll, despite its name, reads its first argument as a regex: . matches any character, ( throws PatternSyntaxException, and $1 in the replacement is a group-reference error.
Plain replace-all is replace.
C and C++ have no replace function: find with strstr/find, append the part before plus b, and search again right after the match.
Searching the result again from the start never ends when the replacement contains the pattern, as with a → aa in "banana".

Pythonmain.py · 4 lines
text = input()a = input()b = input()print(text.replace(a, b))
JavaScriptmain.js · 3 lines
const [text, a, b] = require("fs").readFileSync(0, "utf8").split("\n").map((x) => x.replace(/\r$/, ""));// split/join은 글자를 그대로 쓴다(replaceAll의 둘째 값은 $& $$ 같은 특수 패턴을 해석한다)console.log(text.split(a).join(b));
TypeScriptmain.ts · 4 lines
import { readFileSync } from "node:fs";const [text, a, b]: string[] = readFileSync(0, "utf8").split("\n").map((x) => x.replace(/\r$/, ""));// split/join은 글자를 그대로 쓴다(replaceAll의 둘째 값은 $& $$ 같은 특수 패턴을 해석한다)console.log(text.split(a).join(b));
JavaMain.java · 13 lines
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String text = br.readLine();        String a = br.readLine();        String b = br.readLine();        // replace(CharSequence, CharSequence)는 글자 그대로, 모두 바꾼다(replaceAll은 정규식)        System.out.println(text.replace(a, b));    }}
C#Main.cs · 12 lines
using System; class Program{    static void Main()    {        string text = Console.ReadLine();        string a = Console.ReadLine();        string b = Console.ReadLine();        Console.WriteLine(text.Replace(a, b));    }}
C++main.cpp · 18 lines
#include <iostream>#include <string> int main() {    std::string text, a, b;    std::getline(std::cin, text);    std::getline(std::cin, a);    std::getline(std::cin, b);    std::string out;    size_t from = 0;    for (size_t at = text.find(a); at != std::string::npos; at = text.find(a, from)) {        out.append(text, from, at - from);        out += b;        from = at + a.size();    }    out.append(text, from, std::string::npos);    std::cout << out << "\n";}
Cmain.c · 23 lines
#include <stdio.h>#include <string.h> static void read_line(char *buf, int size) {    if (!fgets(buf, size, stdin)) buf[0] = '\0';    buf[strcspn(buf, "\r\n")] = '\0';} int main(void) {    char text[1005], a[16], b[16];    read_line(text, sizeof text);    read_line(a, sizeof a);    read_line(b, sizeof b);    size_t m = strlen(a);    const char *p = text;    for (const char *q = strstr(p, a); q != NULL; q = strstr(p, a)) {        fwrite(p, 1, (size_t)(q - p), stdout);  /* 찾은 곳 앞까지 */        fputs(b, stdout);        p = q + m;                              /* 찾은 말 다음부터 다시 */    }    puts(p);    return 0;}
Craykonmain.cray · 4 lines
text = Console.ReadLine();a = Console.ReadLine();b = Console.ReadLine();Console.WriteLine(text.Replace(a, b));