fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static String replaceLast(String texto, String substituir, String substituto) {
  11. // Retorna o índice da última ocorrência de "substituir"
  12. int pos = texto.lastIndexOf(substituir);
  13. // Se encontrar o índice
  14. if (pos > -1) {
  15. // Retorna os caracteres antecedentes de "substituir"
  16. return texto.substring(0, pos)
  17. + substituto
  18. // Retorna os caracteres posteriores a "substituir"
  19. + texto.substring(pos + substituir.length(), texto.length());
  20. } else
  21. // Se a palavra especificada em "substituir" não for encontrada não altera nada
  22. return texto;
  23. }
  24. public static void main (String[] args) throws java.lang.Exception
  25. {
  26. String texto = "foobarsin";
  27. if (texto.endsWith("asin")){
  28. System.out.println(replaceLast(texto, "asin", ""));
  29. }
  30. else if (texto.endsWith("sin")){
  31. System.out.println(replaceLast(texto, "sin", ""));
  32. }
  33. }
  34. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
foobar