Search code examples
javastringreplaceall

Advice re replacing all instances of text in Java string using method replaceAll


I need to replace instances of text in a Java string and I am currently using the replaceAll method as follows:

    String originalText = ("The City of London has existed for approximately 2000 years and the City of London remains to this day.");
    String originalKeyword = ("City of London");
    String revisedKeyword = ("");
    if (String_Utils.getLengthOfKeyword(originalKeyword) > 1) {
        revisedKeyword = String_Utils.removeChar(originalKeyword, ' ');
    }
    else {
        revisedKeyword = originalKeyword;        
    }        
    String revisedText = originalText.replaceAll(originalKeyword, revisedKeyword);        
    System.out.println("Original text: " + originalText);
    System.out.println("Revised text: " + revisedText);
    System.out.println("Original keyword: " + originalKeyword);
    System.out.println("Revised keyword: " + revisedKeyword);

The aim of the above is to save a revised version of the original keyword without spaces, and if the number of words in the keyword is more than one, then replace all instances of the original keyword in the string.

Given that this will be a batch operation, does anyone know if there is a better way for bulk-replacing text in a Java string? Or are there any pitfalls concerning replaceAll?


Solution

  • String originalText = ("The City of London has existed for approximately 2000 years and the City of London remains to this day.");
    String originalKeyword = ("City of London");
    String revisedKeyword = ("");
    

    "to save a revised version of the original keyword without spaces"

    String newVersion = new String(originalKeyword);
    revisedKeyword = newVersion.replaceAll(" ","");
    

    "and if the number of words in the keyword is more than one, then replace all instances of the original keyword in the string."

    int lengthWord = originalKeyword.split(" ").length;
    if(lengthWord > 0){ 
        originalText.replaceAll(originalKeyword , revisedKeyword);
    }