Replacement
2 minutos de lectura
Se nos proporciona el siguiente sitio web para escribir una solución de un reto de programación:
Problema
Necesitamos escribir un programa que tome una cadena de texto y dos caracteres adicionales para reemplazar uno para el otro. Por ejemplo:
"asdf" "s" "b"
->"abdf"
Solución
Como nos dejan usar C, C ++, Python y Rust, vamos a escribir una solución en cada lenguaje, porque sí.
C
#include <stdio.h>
int main() {
// take in the strings
char s[1024] = { 0 };
char a;
char b;
fgets(s, sizeof(s), stdin);
scanf("%c\n", &a);
scanf("%c\n", &b);
// calculate answer
int i = -1;
char answer[1024] = { 0 };
while (s[++i]) {
answer[i] = s[i] == a ? b : s[i];
}
// print answer
printf("%s", answer);
return 0;
}
C++
#include <algorithm>
#include <iostream>
int main() {
// take in the string
std::string s;
getline(std::cin, s);
char a = getchar();
getchar();
char b = getchar();
getchar();
// calculate answer
std::string answer = s;
replace(answer.begin(), answer.end(), a, b);
// print answer
std::cout << answer << std::endl;
return 0;
}
Python
# take in the strings
s = input()
a = input()
b = input()
# calculate answer
answer = s.replace(a, b)
# print answer
print(answer)
Rust
use std::io;
fn main() {
// take in the strings
let mut s = String::new();
io::stdin().read_line(&mut s).expect("Failed to read line");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let a = input
.chars()
.nth(0)
.expect("Please enter a valid character");
input.clear();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let b = input
.chars()
.nth(0)
.expect("Please enter a valid character");
// calculate answer
let answer = str::replace(&s.trim(), &a.to_string(), &b.to_string());
// print answer
println!("{}", answer);
}
Flag
Usando cualquiera de estos programas, podemos resolver el reto y capturar la flag:
HTB{r3pLacE_th3_sTR1nG_t0_g3t_th3_bl1ng!!}