Google
[IT] Java - Sostituzione sottostringhe ("String replace")

Java - Sostituzione sottostringhe ("String replace")


La sostituzione e' forse una delle operazioni piu' comunemente effettuate su stringhe.
Il problema da risolvere e': data una stringa, sostituire tutte le occorrenze di un certa sottostringa con un altro testo.
Il metodo fa parte della classe StringUtil del progetto FAS.
  /**
   * Sostituisce in source tutte le occorrenze di oldstr con newstr.
   * @param source e' la stringa iniziale
   * @param oldstr e' la sottostringa da cercare
   * @param newstr e' la sottostringa da mettere al posto di "oldstr"
   * @return una nuova stringa con le sostituzioni effettuate.
   */
  public static String replace( String source, String oldstr, String newstr ) {
      StringBuffer sb = new StringBuffer();
      int old = 0;
      int pos = 0;
      while ( ( pos = source.indexOf( oldstr, old ) ) != -1 ) {
          sb.append( source.substring( old, pos ) );
          sb.append( newstr );
          old = pos + oldstr.length();
      }
      sb.append( source.substring( old ) );
      return sb.toString();
  }
Home Giansante Gabriele (c) 1999-2006