pangfengliu / programmingtasks

programming tasks from my courses
67 stars 17 forks source link

String Substitution #345

Open littlehug opened 5 years ago

littlehug commented 5 years ago

Write a program to replace a part of a string with another string.

Task Description

We will apply a series of commands on a string S of length L. There are two commands. The first command is p (print), which will simply print the string S. The other command is s (substitute), which will replace the first occurrence of a string A in S with another string B. The s command starts with a character ‘s’, and the first character after ‘s’ is the delimiter, which will separate the two strings A and B. For example, s/cd/ef/ has / as the delimiter, A as cd and B as ef. Therefore we will replace the first occurrence of cd in S with ef. Note that the delimiter is the first character after 's' so it can be any character. For example, if S is qwerasdfqwerzxcv and the instruction is s%qwer%zxcv%, then the delimiter is %, and A and B are qwer and zxcv, respectively. Finally S will become zxcvasdfqwerzxcv. Also note that if there is no A in S then S remain unchanged.

The following example list the commands and the outcome of the commands.

string S command delimiter result output
qwerasdfqwerzxcv s%qwer%zxcv% % zxcvasdfqwerzxcv
zxcvasdfzxcvzxcv sazxca%a a %vasdfqwerzxcv
%vasdfqwerzxcv p %vasdfqwerzxcv
%vasdfqwerzxcv s3123asdf3 3 %vasdfqwerzxcv

Subtask

Input Format

The input contains only one test case. The first line contains the string S. The rest of the input has a series of commands. Each line has one command. It is guaranteed that the length of string S will not exceed 1023 during the operations.

1 < L < 1024
1 < length of string in each instruction < 501

Output Format

Print the current string if the instruction is ‘p’.

Sample Input 1

abbcccddddeeeeeffffff
s%ccc%a%
p
s/d/k/
p
Sefffefe
p
s~a~0~
p

Sample Output 1

abbaddddeeeeeffffff
abbakkkkeeeeeffffff
abbakkkkeeeeeff
0bbakkkkeeeeeff

Sample Input 2

Abbcccddddeeeeeffffff
s%ccc%kkk%
p
s/dd/cc/
p
skqwerkasdfk
p

Sample Output 2

Abbkkkddddeeeeeffffff
Abbkkkcccceeeeeffffff
Abbkkkcccceeeeeffffff

Sample Input 3

qwerasdfzxcv
s%qwer%asd%
p
soasdasdfzxcvoasdasdfzxcveo
p
stasdasdfzxcve3tasdasdfzxcvet
p

Sample Output 3

asdasdfzxcv
asdasdfzxcve
asdasdfzxcve