Untitled
user_6122548
plain_text
2 years ago
2.7 kB
13
Indexable
import java.util.Scanner;
public class Ja_01_secret_chat {
public static String ubaciRazmak (String poruka, int indeks){
StringBuilder sbSaRazmakom = new StringBuilder(poruka);
sbSaRazmakom.insert(5, " ");
return sbSaRazmakom.toString();
} public static String reverse (String poruka, String substring){
if (!poruka.contains(substring)) {
System.out.println("Error"); return poruka;
} else {
StringBuilder sb = new StringBuilder(substring);
String obrnutiSubstring = sb.reverse().toString();
poruka = poruka.replaceFirst(substring, obrnutiSubstring);
} return poruka;
} public static String cnangeAll(String poruka, String substring, String zamena) {
poruka = poruka.replaceAll(substring, zamena);
return poruka;
//Reverse:|:?uoy
}
public static void main(String[] args) {
//• "InsertSpace:|:{index}":
//o Inserts a single space at the given index. The given index will always be valid.
//• "Reverse:|:{substring}":
//o If the message contains the given substring, cut it out, reverse it and add it at the end of the message.
//o If not, print "error".
//o This operation should replace only the first occurrence of the given substring if there are two or more occurrences.
//• "ChangeAll:|:{substring}:|:{replacement}":
//o Changes all occurrences of the given substring with the replacement text.
Scanner sc = new Scanner(System.in);
String poruka = sc.nextLine();
while (true) {
String unos = sc.nextLine();
if (unos.equals("Reveal")) break;
String [] nizKomandi = unos.split(":\\|:");
String komanda = nizKomandi[0];
if (komanda.equals("InsertSpace")) {
int indeksZaRazmak = Integer.parseInt(nizKomandi[1]);
poruka=ubaciRazmak(poruka, indeksZaRazmak);
System.out.println(poruka);
} else if (komanda.equals("Reverse")){
String substring = nizKomandi[1];
poruka = reverse(poruka, substring);
System.out.println(poruka);
} else if (komanda.equals("ChangeAll")){
//"ChangeAll:|:{substring}:|:{replacement}":
String substring = nizKomandi[1];
String zamena = nizKomandi[2];
poruka = cnangeAll(poruka, substring, zamena);
System.out.println(poruka);
}
}
System.out.printf("You have a new text message: %s\n", poruka);
}
}
Editor is loading...