lstIQCodes = IQcodeString.replaceAll(' ','').split(',');
I have tried the above code and able to replace spaces and now I want to replace newline as well.
If you just want to get rid of all the white space, you can just delete it:
lstIQCodes = IQcodeString.deleteWhitespace().split(',');
ReplaceAll actually takes a regular expression for the first parameter, so the following is also valid:
lstIQCodes = IQcodeString.replaceAll('\\s+','').split(',');
\\s
refers to all white space, including tabs, new lines, carriage returns, and spaces.
Or, if you really just wanted spaces and newlines:
lstIQCodes = IQcodeString.replaceAll('[\\n ]+','').split(',');
split
is not really appropriate.
You can follow the same approach to remove the new lines as well
for(String lines : IQcodeString.replaceAll(' ','').split(','))
system.debug(lines.replaceAll('\n','').replaceAll('\r','') );
Here is a sample utility function for this specifically because of the presence of the legacy carriage return character (ASCII 13) I was seeing in data.
public static String removeAsciiCharFromString(String str, Integer c) {
String ret = '';
List<Integer> chars = new List<Integer>();
for (Integer i = 0; i < str.length(); i++) {
if (str.charAt(i) != c) {
chars.add(str.charAt(i));
}
}
ret = String.fromCharArray(chars);
return ret;
}
Usage:
String test = String.fromCharArray(new List<Integer> { 65, 13, 65 });
String expected = 'AA';
String actual = UtilConvert.removeAsciiCharFromString(test, 13);
System.assertEquals(expected, actual);
Of course you can pass in any ASCII value, such as 32 for whitespace.