To remove leading or trailing white space characters using Apex in Salesforce, trim() is used.
Sample Code:
String str1 = ‘ test ‘;
String str2 = str1.trim(); //test will be output without any white spaces
Cheers!!!