0

in the code example below would converting the function to use StringBuilder make it more efficient and be worth it? and

how to convert the convertStringToInputString function to use StringBuilder? StringBuilder does not have a replace method.

   // converts String to type of String that can be inserted into database, no space, no eof characters
public String convertStringToInputString(String standardString){
    String str = standardString.replace(" ", "XspaceX");
    String str2 = str.replace("\n", "XendoflineX");
    return str2;
}

  // fills table with information to be put into JSON String object
public void fillTable(){

    initialField.a[0] = convertStringToInputString("");
    initialField.a[1] = convertStringToInputString("");
    initialField.a[2] = convertStringToInputString("");
    initialField.a[3] = convertStringToInputString("");
    initialField.a[4] = convertStringToInputString("");
    initialField.a[5] = convertStringToInputString("");
    initialField.a[6] = convertStringToInputString("");
    initialField.a[7] = convertStringToInputString("");
    initialField.a[8] = convertStringToInputString("");
    initialField.a[9] = convertStringToInputString("");
    // continue with more 120 more lines like this
Kevik
  • 9,181
  • 19
  • 92
  • 148
  • see [Replace all occurences of a String using StringBuilder?](http://stackoverflow.com/questions/3472663/replace-all-occurences-of-a-string-using-stringbuilder/3472705#3472705) – ρяσѕρєя K May 31 '13 at 04:32
  • Unless this encoding scheme is too deeply incorporated into the software already, you might want to consider using a more standard encoder like `java.net.URLEncoder.encode()`. – Michael Burr May 31 '13 at 04:57

3 Answers3

1

Why not just inline your string manipulations? I think it improves readability and avoids creating unnecessary functions and objects.

initialField.a[0] = string.replace(" ","space").replace("\n","newline");

SoundsDangerous
  • 708
  • 6
  • 13
0

I don't understand what you are doing, but you could use stringbuilder's append method like so:

public String toString(whateverType initialField) {
    StringBuilder sB = new StringBuilder();
    for (int i = 0; i<initialField.length; i++) {
        sB.append(initialField[i];
    }
    String str2 = sB.toString();
    return str2;
}
nexus_2006
  • 744
  • 2
  • 14
  • 29
0

you can use

StringBuilder.replace(int start, int end, String str)

here

start - The beginning index, inclusive.

end - The ending index, exclusive.

str - String that will replace previous contents.

So you can use StringBuilder.indexOf method to find the index then use the above method to replace it.

Community
  • 1
  • 1
stinepike
  • 54,068
  • 14
  • 92
  • 112