• Articles
  • Tutorials
  • Interview Questions

What is Apex String Class in Salesforce?

What is Apex String Class in Salesforce?

Salesforce CRM helps thousands of companies around the world discover new opportunities, create marketing campaigns, manage and use customer data, and improve communication (internal and external). Ultimately, it helps them improve their decision-making skills and fuel stronger business growth. In Salesforce there is an important concept that deals with many predefined methods to make the work easier in Salesforce. This is known as Apex String Methods.

Watch this Salesforce Training video and learn all about Salesforce:

Video Thumbnail

What is Apex String Class in Salesforce?

String Class Salesforce is basically a class variable that consists of various Apex String Methods and these particular String methods Salesforce allows Alt-text users to perform multiple operations in different strings. So when these String Methods combine together they make a string class in Salesforce.

Check out our Salesforce Certification!

What are String Methods?

The String is a set of characters that have no limits. There are various methods for String in Salesforce.

abbreviate

There are two versions of this method:

  1. abbreviate(maxWidth) – This method returns the abbreviated version of the string in the length that is specified. In case the string is longer than the width that is set, it comes back with ellipses, otherwise, it returns the original string.
    For example:
    String s = 'Hello World';
    String s2 = s.abbreviate(8);
    System.assertEquals('Hello...', s2);
    System.assertEquals(8, s2.length());
  2. abbreviate(maxWidth, offset) – This method returns the abbreviated version of the string that starts at the specified character offset, of the given length. There are ellipses at the beginning and end of the returned version if the characters have been removed from these places.
    For example:
    String s = 'Hello America';
    // Start at A
    String s2 = s.abbreviate(9,6);
    System.assertEquals('...Ame...', s2);
    System.assertEquals(9, s2.length());

Capitalize

capitalize() returns the string with its first letter capitalized.

For example:

String s = 'hello world';
String s2 = s.capitalize();
System.assertEquals('Hello world', s2);

Center

There are two versions of this string method:

  1. center(size) - This returns the string of the given size, with spaces at the beginning and end of the string, so that it appears to be in the center. If the given size is smaller than the string then the string is returned as is without the spaces.
    For example:
    String s = 'world';
    String s2 = s.center(11);
    System.assertEquals(
    ' world ',
    s2);
  2. center(size, paddingString) - This returns the string of the given size, with the padding string at the beginning and end of the original string, so that it appears to be in the center. If the given size is smaller than the string then the string is returned as it is without the padding string.
    For example:
    String s = 'world';
    String s2 = s.center(9, '+');
    System.assertEquals('++world++', s2);

CharAt

charAt(index) string method returns the value of the character at the index given.

For example:

String str = 'Hello Intellipaat.';
System.assertEquals(937, str.charAt(0));

codePointAt

codePointAt returns the value of the Unicode at the given index.

For example:

String str = 'Hello';
System.assertEquals(72, str.codePointAt(0));

compareTo

compareTo(secondString) compares two strings in the dictionary order based on their Unicode values.

For example:

String myString1 = 'hello';
String myString2 = 'hemlo';
Integer result =
 myString1.compareTo(myString2);
System.assertEquals(result, -1);

Salesforce Master Course

Contains

contains(substring) returns true if the string that called this method contains the characters in the same sequence as the substring specified.

For example:

String myString1 = 'public';
String myString2 = 'pub';
Boolean result =
 myString1.contains(myString2);
System.assertEquals(result, true);

countMatches

countMatches(substring) returns the value as the number of times that the substring appears in the string that is called the method.

For example:

String s = 'Hey Hi';
System.assertEquals(1, s.countMatches('Hey'));
s = 'Hey Hey';
System.assertEquals(2, s.countMatches('Hey'));
s = 'Hey hey';
System.assertEquals(1, s.countMatches('Hey'));

deleteWhitespace

deleteWhitespace() removes the whitespaces from the string.

For example:

String s1 = ' Hello World '; String s2 = 'HelloWorld'; System.assertEquals(s2, s1.deleteWhitespace());

difference

difference(secondString) returns the difference between the first and the second string.

For example:

String s = 'Hello World'; String d1 = s.difference('Hello India'); System.assertEquals( 'India', d1); String d2 = s.difference('Goodbye'); System.assertEquals( 'Goodbye', d2);

endsWith

endsWith(suffix) compares the given string with a specified suffix and returns true only if the string ends with the suffix.

For example:

String s = 'Hello World'; System.assert(s.endsWith('World'));

equals

equals(stringOrld) is used when you want to compare an object that is a string or an ID, to a given string.

For example:

// Compare a string to an object containing a string

Object obj = 'xyz';
String str = 'xyz';
Boolean result1 = str.equals(obj);
System.assertEquals(true, result1);
// Compare a string to an object containing a number
Integer obj1 = 100;
Boolean result2 = str.equals(obj1);
System.assertEquals(false, result2);
// Compare a string to an ID of the same length.
// 15-character ID
Id id = '001D000000Ju1zH';
// 15-character ID string value
String string = '001D000000Ju1zH';
Boolean result3 = string.equals(Id);
System.assertEquals(true, result3); 
// Compare two equal ID values of different lengths:
//  15-character ID and 18-character ID
Id id18 = '001D000000Ju1zHIAR';
Boolean result4 = string.equals(Id18);
System.assertEquals(true, result4);
Object obj = 'xyz';
String str = 'xyz';
Boolean result1 = str.equals(obj);
System.assertEquals(true, result1);
// Compare a string to an object containing a number
Integer obj1 = 100;
Boolean result2 = str.equals(obj1);
System.assertEquals(false, result2);
// Compare a string to an ID of the same length.
// 15-character ID
Id id = '001D000000Ju1zH';
// 15-character ID string value
String string = '001D000000Ju1zH';
Boolean result3 = string.equals(Id);
System.assertEquals(true, result3); 
// Compare two equal ID values of different lengths:
//  15-character ID and 18-character ID
Id id18 = '001D000000Ju1zHIAR';
Boolean result4 = string.equals(Id18);
System.assertEquals(true, result4);

indexOf

There are two versions of this string method:

  1. indexOf(substring) - This string method returns the index of when the first time the substring occurred.
    For example:
    String myString1 = 'pqrst';
    String myString2 = 'rs';
    Integer result = myString1.indexOf(mystring2);
    System.assertEquals(2, result);
  2. indexOf(substring, index) - This string method returns the index of when the first time the substring occurred from the given index.
    For example:
    String myString1 = 'lmnolmrs';
    String myString2 = 'lm';
    Integer result = myString1.indexOf(mystring2, 1);
    System.assertEquals(4, result);

Get 100% Hike!

Master Most in Demand Skills Now!

valueOf

There are various versions of this string method:

  1. valueOf(dateToConvert) - This method returns a date specified in the string in the format of “yyyy-mm-dd”.
    For example:
    Date myDate = Date.Today();
    String sD = String.valueOf(myDate);
  2. valueOf(datetimeToConvert) - This method returns a date specified in the string in the format of “yyyy-mm-dd hh:mm:ss” according to the local time zone.
    For example:
    DateTime dt = datetime.newInstance(1995, 2, 25);
    String sDT = String.valueOf(dt);
    System.assertEquals('1996-02-25 00:00:00', sDT);
  3. valueOf(decimalToConvert) - This method returns the string that has the value of the given Decimal.
    For example:
    Decimal dec = 3.1415;
    String sDecimal = String.valueOf(dec);
    System.assertEquals('3.1415', sDecimal);
  4. valueOf(doubleToConvert) - This method returns the given Double.
    For example:
    Double myDouble = 10.32;
    String myString =
    String.valueOf(myDouble);
    System.assertEquals(
    '10.32', myString);
  5. valueOf(integerToConvert) - This method returns the string that has the value of the given Integer.
    For example:
    Integer myInteger = 25;
    String sInteger = String.valueOf(myInteger);
    System.assertEquals('25', sInteger);\
  6. valueOf(longToConvert) - This method returns the string that has the value of given Long.
    For example:
    Long myLong = 987654321;
    String sLong = String.valueOf(myLong);
    System.assertEquals('987654321', sLong);
  7. valueOf(toConvert) - This method returns a string that represents the given object argument.
    For example:
    List<Integer> ls =
    new List<Integer>();
    ls.add(30);
    ls.add(40);
    String strList =
    String.valueOf(ls);
    System.assertEquals(
    '(30, 40)', strList);

Get to know more about Salesforce Data Type from our blog- Salesforce Data Types and Field Types!

List of Apex String Methods Salesforce-

There are different types of Apex String Methods in Apex String Class that allow the users to deal with various predefined methods. These predefined methods are Salesforce apex string methods.

Some of the popular Apex String Methods are listed below-

  • contains – The contains method will return the value True if the given string is present in the substring. Example –
String myProduct1 = ‘Salesforce';
String myProduct2 = 'Intllipaat Salesforce Course';
Boolean result = myProductName2.contains(myProduct1);
System.debug('Output will be true as it contains the String and
Output is:'+result);
  • charAt(index) – The charAt method allows the return of the value of the character specified in the particular index. Example-
String str = 'Hello Intellipaat.';
System.assertEquals(937, str.charAt(0));
  • equals – The equals method allows returning true value if the given string and the string passed in the method have the same binary sequence of characters.

Want to know more about Salesforce? Read this extensive Salesforce Tutorial and enhance your knowledge!

Note – The values must not be NULL, also, it is case sensitive.

String string1 = 'Intellipaat';
String string2 = 'Intellipaat';
Boolean result = string2.equals(string1);
System.debug('Value of Result will be true as they are same and Result is:'+result);
  • equalsIgnoreCase – This method will return true if stringtoCompare has the same sequence of characters as the given string.

Note – this method is not case-sensitive.

        String string1 = 'intellipaat';
	String string2 = 'INTELLIPAAT';
	Boolean result =
	myString1.equalsIgnoreCase(string2);
	System.assertEquals(result, true);
  • remove – This method deletes the string specified by stringToRemove from the specified string. This is useful when you want to delete certain characters from a string and you don’t know the exact index of the character to be deleted.

Preparing for a Salesforce Interview! Check out our Salesforce Interview Questions.

Note - This method is case-sensitive. If the same string appears but the case is different, this method will not work as a string method in Salesforce

String s1 = 'Salesforce and force.com';
	String s2 =
	  s1.remove('force');
	System.assertEquals(
	  'Sales and .com', s2);
  • indexOf – Returns the index of the first occurrence of the specified substring. If the substring does not occur, this method returns -1. Example-
String myString1 = 'abcde';
	String myString2 = 'cd';
	Integer result = myString1.indexOf(mystring2);
	System.assertEquals(2, result);
  • startsWith – This method will return true if the given string starts with the prefix provided in the method.

Note - Method is not case sensitive.

String s1 = 'Salesforce and Intellipaat';  
System.assert(s1.startsWith('Salesforce'));
  • isAllUpperCase() This string method will return True if the string contains all characters in uppercase.
//Return true
String s1 = 'INTELLIPAAT';
Boolean b1 = s1.isAllUpperCase()
  • isAllLowerCase() - This string method will return True if the string contains all characters in lowercase.
//Return true
String s1 = 'intellipaat';
Boolean b1 = s1.isAllLowerCase()

Check out our blog on Salesforce Admin Interview Questions and Answers and ace your interview in your job interview.

What are access modifiers in Salesforce?

There are various access modifiers in Salesforce which provide data security and maintain data integrity in an enterprise. The access modifiers provide different access to different people according to their job roles. The access specifiers in Salesforce are-

  • Private - This is the default, associate degreed means the tactic or variable is accessible solely at intervals in the apex string class category within which it’s defined. If you do not specify an access modifier, the method or variable is private automatically.
  • Protected - This means that the variable is visible to any inner categories within the specified Apex class, and to the classes that stretch the defining Apex String class in Salesforce. You’ll be able to solely use this access modifier, let’s say ways and member variables. Note that it’s strictly more permissive than the default (private) setting, a bit like Java.
  • Global - This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application.
  • Public - This means the method or variable can be used by any Apex in this application or namespace. In Apex, if you want to make something public like it is in Java, you need to use the global access modifier.

Example of public and private access specifiers in Salesforce:

// private variable s1
	private string s1 = '1';
	 
	// public method sales()
	public string sales() {
	  ...
	}

Do you want to build a career in Salesforce? Enroll in this Salesforce Training in Bangalore to start your journey!

Conclusion

The Apex String Methods in Salesforce have made the job easy for a lot of people and organizations. The various string methods in Salesforce help companies make their job a lot easier and quicker. Multiple operations can be combined together in a string class to make the work efficient. The access modifiers in Salesforce, on the other hand, help make the organizations more secure and maintain data integrity.

Course Schedule

Name Date Details
Salesforce Certification 23 Nov 2024(Sat-Sun) Weekend Batch View Details
30 Nov 2024(Sat-Sun) Weekend Batch
07 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Salesforce Certified Professional

Rahul is a seasoned Salesforce Certified administrator and app builder with 10+ years of experience in many Salesforce technologies, such as Salesforce CRM and business process automation. In his free time, he likes to write and read about the latest technologies.