1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 | package Torello.Java;
class LeftTrimAll
{
static String run(String s)
{
char[] cArr = s.toCharArray();
// LEFT TRIM is easier on the mind. There are only two variables needed for this one.
int targetPos = 0;
int sourcePos = 0;
// Make sure to skip completely any and all leading new-line characters.
while ((targetPos < cArr.length) && (cArr[targetPos] == '\n')) targetPos++;
// If there were **ONLY** leading new-line characters, return the original string
if (targetPos == cArr.length) return s;
// Re-initialize 'sourcePos'
sourcePos = targetPos;
while (sourcePos < cArr.length)
{
// When this loop begins, sourcePos is pointing at the first character of text
// in the very-next line-of-text to process.
//
// NORMAL EXECUTION: This loop advances 'sourcePos' to the first non-white-space
// character in the line.
//
// WS-ONLY LINES CASE: This loop advances 'sourcePos' to the next line ('\n')
//
// LAST-LINE CASE: Advances 'sourcePos' to cArr.length
while ( (sourcePos < cArr.length)
&& Character.isWhitespace(cArr[sourcePos])
&& (cArr[sourcePos] != '\n')
)
sourcePos++;
// Left Shift the String to 'erase' all leading white-space characters in the
// current line of text.
while ((sourcePos < cArr.length) && (cArr[sourcePos] != '\n'))
cArr[targetPos++] = cArr[sourcePos++];
// The loop that is directly above this statement BREAKS when '\n' is reached,
// so unless the end of the String has been reached, shift one more of the characters
// NOTE: If a character is shifted, below, it will always be the '\n' character
if (sourcePos < cArr.length) cArr[targetPos++] = cArr[sourcePos++];
}
return new String(cArr, 0, targetPos);
}
}
|