I have a very long String that I want to manipulate in Java. Then row length of this file is 2179 characters.
My program shall replace substrings in that file from a specific start position to an end position.
I have written methods for that but it doesn't work.
After processing my method the row the row is longer than 2179.
For every field I want to replace a string with the row length will be longer!
Why? Is there another why of doing this?
If this is some kind of assignment where you need to do it manually, I am not allowed to just give you a working example here so here I go with hints:
1) constantly re-arranging your StringBuffer like you do is inefficient.
set a start variable to 0
while ( indexOfStringReplace != -1 )
-search for next indexOfStringToReplace in your string starting at start
-append substring(start,indexOfStringToReplace) to your StringBuffer
-append the new string (new value) to your StringBuffer
-set start to indexOfStringToReplace+lenght of the String you were looking for to replace
if (start < originalString.length) //otherwise you had a string to replace at the very end of your string
-Then add the remaining of the string to your string buffer e.g. originalString.substring(start,originalString.length())
2) That's it, you are done. The idea is to iterate in your String to find all occurrence of stringToReplace then, append (build) to your String buffer
3) Don't replace and search in your StringBuffer, just append to it and search in the String instead.
It looks to me like you want to take the "string to replace" and fix it so it's exactly 7 characters long, padding with extra "0" at the beginning if it's too short and truncating if it's too long. Is that right? If so, your way is hard to follow and I think there are easier ways. (If not, then that's because your way is hard to follow )
And then if END_POS - START_POS doesn't refer to 7 characters in the StringBuilder, you're going to change the length of the result by hard-coding "7" in your code. So you shouldn't hard-code the length you expect to replace, you should compute it from the field size.