You can use the instance method "trim" on the String class.
According to the docs:
"Returns a copy of the string that no longer contains any leading or trailing white space characters.
Leading and trailing ASCII control characters such as tabs and newline characters are also removed. Whitespace and control characters that aren’t at the beginning or end of the sentence aren’t removed."
// Example
String str = ' whatever ';
System.debug('the trimmed output is: ' + str.trim()); // outputs : the trimmed output is:whatever
The trim method is only useful if you want to remove leading and/or trailing spaces. If you want to remove whitespace between a string (for e.g. 'remove this space'. Then you'd have to use 'split' as follows:
// remove space between strings example
String str = 'remove this space';
String[] splitString = str.split(' ');
for(String s: splitString) {
str = str+s;
}
system.debug('the string is: '+str); // outputs - the string is: removethisspace
In such cases the best thing would be to introduce yourself with regular expressions. It's simple, it's powerfull and it works.
String sText = 'fdsafas fdsafds f fdsafas fdafdsa ';
sText= sText.replaceAll( '\\s+', '');
System.debug('*********************' + sText);
WIth \\s+ it will find all spaces in the string and replace it with empty string.
All Answers
"trim" in general...this is an instance method and remove leading and trailing white spaces
string str = ' hai';
str = str.trim(); will gives you 'hai'
You can use the instance method "trim" on the String class.
According to the docs:
"Returns a copy of the string that no longer contains any leading or trailing white space characters.
Leading and trailing ASCII control characters such as tabs and newline characters are also removed. Whitespace and control characters that aren’t at the beginning or end of the sentence aren’t removed."
// Example
String str = ' whatever ';
System.debug('the trimmed output is: ' + str.trim()); // outputs : the trimmed output is:whatever
Hope this helps!!
The trim method is only useful if you want to remove leading and/or trailing spaces. If you want to remove whitespace between a string (for e.g. 'remove this space'. Then you'd have to use 'split' as follows:
// remove space between strings example
String str = 'remove this space';
String[] splitString = str.split(' ');
for(String s: splitString) {
str = str+s;
}
system.debug('the string is: '+str); // outputs - the string is: removethisspace
In such cases the best thing would be to introduce yourself with regular expressions. It's simple, it's powerfull and it works.
String sText = 'fdsafas fdsafds f fdsafas fdafdsa ';
sText= sText.replaceAll( '\\s+', '');
System.debug('*********************' + sText);
WIth \\s+ it will find all spaces in the string and replace it with empty string.
The code above will return: HowAreYouToday?