Cheatsheet

substring() and trim()

Estimated reading: 1 minute 29 views
				
					String substring(Integer startIndex);
String substring(Integer startIndex, Integer endIndex);

				
			
  • startIndex: The index where the substring starts (0-based index).
  • endIndex (optional): The index where the substring ends (exclusive).
				
					String productCode = 'PRD-12345-US';
// Extracting the product type (first 3 characters)
String productType = productCode.substring(0, 3);
System.debug('Product Type: ' + productType);  // Output: PRD

// Extracting the product number (characters from index 4 to 9)
String productNumber = productCode.substring(4, 9);
System.debug('Product Number: ' + productNumber);  // Output: 12345

// Extracting the country code (characters after the last dash)
String countryCode = productCode.substring(10);
System.debug('Country Code: ' + countryCode);  // Output: US

				
			
				
					String customerName = '   John Doe   ';
System.debug('Original Name: [' + customerName + ']');  // Output: [   John Doe   ]

// Removing leading and trailing spaces
String trimmedName = customerName.trim();
System.debug('Trimmed Name: [' + trimmedName + ']');  // Output: [John Doe]
				
			

Combining substring() and trim()

				
					String rawString = '  testXYZ startlight X  ';

// Find the index of the first occurrence of 'Oto'
Integer index = rawString.indexOf('Oto');

// Extract the part after 'Oto' and trim the result
String dealerName = rawString.substring(index + 3).trim();

System.debug('Dealer Name: [' + dealerName + ']');  // Output: [Değerlendirme X]

				
			
Share this Doc

substring() and trim()

Or copy link

CONTENTS