3
18/10/2024 9:34 am
Topic starter
Create a program that executes changes over a string.
First, you start with an empty string, then you receive the commands.
You will be receiving commands until the "End" command. There are five possible commands:
- "Add {string}"
- Concatenate {string} to the string.
- "Upgrade {char}"
- Find all occurances of {char} and replace it with the ASCII code plus one.
- "Print"
- Print the string.
- "Index {char}"
- Find all the indeces where {char} occurs, then print them separated by a space if no occurances – print "None".
- "Remove {string}"
- Remove all occurances of {string} from the string.
Input:
- On each line, until the "End" command is received, you will be receiving commands.
- All commands are case sensitive.
- The input will always be valid.
Output:
- Print the output of every command in the format described above.
Examples:
1 Answer
2
18/10/2024 9:40 am
Here is my solution:
<?php $string = ""; $input = readline(); while ($input != "End") { $args = explode(" ", $input); $command = $args[0]; switch ($command) { case 'Print': echo $string . PHP_EOL; break; case 'Add': $concat = $args[1]; $string .= $concat; break; case 'Upgrade': $char = $args[1]; $replace = chr(ord($char) + 1); $string = str_replace($char, $replace, $string); break; case 'Index': $indeces = []; $search = $args[1]; for ($i = 0; $i < strlen($string); $i++) { if ($string[$i] == $search) { $indeces[] = $i; } } if (count($indeces) > 0) { echo implode(" ", $indeces) . PHP_EOL; } else { echo "None"; } break; case 'Remove': $remove = $args[1]; $string = str_replace($remove, "", $string); break; } $input = readline(); }