0
 lstIQCodes = IQcodeString.replaceAll(' ','').split(','); 

I have tried the above code and able to replace spaces and now I want to replace newline as well.

3 Answers 3

1

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(','); 
1
  • 1
    Exactly what I would have recommended as well. Using split is not really appropriate.
    – Adrian Larson
    Jun 26, 2018 at 6:32
0

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','') );
0

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .