1 package com.github.mygreen.supercsv.cellprocessor.conversion;
2
3 import org.supercsv.cellprocessor.CellProcessorAdaptor;
4 import org.supercsv.cellprocessor.ift.CellProcessor;
5 import org.supercsv.cellprocessor.ift.StringCellProcessor;
6 import org.supercsv.util.CsvContext;
7
8
9
10
11
12
13
14
15 public class OneSideTrim extends CellProcessorAdaptor implements StringCellProcessor {
16
17
18
19
20 private final char trimChar;
21
22
23
24
25
26 private final boolean leftAlign;
27
28
29
30
31
32
33
34 public OneSideTrim(final char trimChar, final boolean leftAlign) {
35 super();
36 this.trimChar = trimChar;
37 this.leftAlign = leftAlign;
38 }
39
40
41
42
43
44
45
46
47 public OneSideTrim(final char trimChar, final boolean leftAlign, final StringCellProcessor next) {
48 super(next);
49 this.trimChar = trimChar;
50 this.leftAlign = leftAlign;
51 }
52
53
54
55
56 @Override
57 public <T> T execute(final Object value, final CsvContext context) {
58
59 if(value == null) {
60 return next.execute(value, context);
61 }
62
63 final String result = trim(value.toString());
64 return next.execute(result, context);
65 }
66
67
68
69
70
71
72 private String trim(final String str) {
73
74 final int length = str.length();
75 if(length == 0) {
76 return str;
77 }
78
79 if(leftAlign) {
80 if(str.charAt(0) != trimChar) {
81
82 return str;
83
84 }
85
86
87 for(int i=0; i < length; i++) {
88 char c = str.charAt(i);
89 if(c != trimChar) {
90 return str.substring(i);
91 }
92 }
93
94
95 return "";
96
97 } else {
98 if(str.charAt(length - 1) != trimChar) {
99
100 return str;
101
102 }
103
104
105 for(int i=length - 1; i >= 0; i--) {
106 char c = str.charAt(i);
107 if(c != trimChar) {
108 return str.substring(0, i + 1);
109 }
110 }
111
112
113 return "";
114
115 }
116
117 }
118
119
120
121
122
123 public char getTrimChar() {
124 return trimChar;
125 }
126
127
128
129
130
131 public boolean isLeftAlign() {
132 return leftAlign;
133 }
134
135
136
137 }