So starting off, here's a simple one I need at the moment. I have a string coming in from a USB serial port in the format:
DATE TIME MEASUREMENT1 MEASUREMENT2 MEASUREMENT3 SO
I need to split the string and parse the measurements, but the multiple and variable number of spaces is really throwing things off. So my goal is to output only one space for each segment of multiple spaces. Here is my code in O(n) linear time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public static String removeMultipleSpaces(String str){ StringBuffer sb = new StringBuffer(); int i = 0; boolean firstSpace = false; while (i < str.length()) { if (str.charAt(i) != ' ') { // if not a space, then copy the character and mark flag as true sb.append(str.charAt(i)); firstSpace = true; } else { // if this is a space and this is the first instance of the space // since the last group, then copy the character as well, but mark // the flag to false if (firstSpace) { sb.append(str.charAt(i)); firstSpace = false; } } i++; } return sb.toString(); } |
Basically as the string is being traversed, a boolean flag determines whether the space I examine is the first space or subsequent spaces. Whenever I detect a character, the flag is set to true again, meaning the first space we see from that point will be kept. And the output I get from this is then:
DATE TIME MEASUREMENT1 MEASUREMENT2 MEASUREMENT3 SO
No comments :
Post a Comment