I am trying to remove all spaces from the following string:
howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;; ;;; :: :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan
and from the place where there are multiple spaces it is removed only one space and the result is:
replaceAll('\s+', '');
replaceAll('[ ]+', '');
replace(' ', '');
and few more similar expressions.
At the moment I'm using the following source code:
String domain = accountObj.Domain__c;
System.debug('domain ' + domain);
integer spaceInd = domain.indexOf(' ');
System.debug('spaceInd1: ' + spaceInd);
while (spaceInd > -1) {
domain = domain.replace(' ', '');
spaceInd = domain.indexOf(' ');
System.debug('spaceInd: ' + spaceInd);
}
System.debug('domain1 ' + domain);
When I start the code in debug log I get the following:
USER_DEBUG|[198]|DEBUG|domain howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;; ;;; :: :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan
USER_DEBUG|[203]|DEBUG|spaceInd1: 75 USER_DEBUG|[207]|DEBUG|spaceInd: -1 USER_DEBUG|[209]|DEBUG|domain1 howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,::::;; ;;;:: :::;;;,,,,,,,,asdasd.asd,,,,,,asdsadas,,,dilyan
Could you please advise how to remove all spaces from the String or replace them with a single space in apex?
Regards,
Diyan
Have you tried the deleteWhiteSpace string method?
This unit test passes for me :
@isTest
private class StringTest
{
static testMethod void myStringTest()
{
String test = 'howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,: :: :;; ;;; :: :: :; ; ;,, ,,, ,,, asdasd.asd,,, ,,,asdsadas,,,dilyan';
String noSpaces = test.deleteWhitespace();
System.assertEquals(noSpaces, 'howabountnow.com,,,itsme.com,,,name,,,hello.com,,,asdasdasdasd.asdasdasda,::::;;;;;:::::;;;,,,,,,,,asdasd.asd,,,,,,asdsadas,,,dilyan');
}
}