· development · 1 min read
Salesforce Apex String Contains Method Explained By Examples
How to check if a string contains a substring in Apex by using the contains method. We introduce the contains method and take a look at examples on how to use contains with strings in Apex.
Apex String Contains Method
Let’s start by taking a look at the details of the contains method of the String class.
<String>.contains
Boolean contains(String substring))
Checks whether a given substring is part of this string or not.
Input parameter
- substring (String): The substring that might be part of this string.
Return value
- Boolean: True, if this strings contains the given substring. False, if the substring is not part of the string.
Example
String fruits = 'apple,banana,orange';
Boolean result = fruits.contains('banana');
System.assertEquals(true,result);
result = fruits.contains('melon');
System.assertEquals(false, result);
Case sensitivity
You might asked yourself: Is contains case-sensitive? Yes, it is.
See the code example:
System.assertEquals(true,'abc'.contains('a'));
System.assertEquals(false,'abc'.contains('A'));
Examples - Apex String contains method
Case-insensitive contains
How to do case-insensitive contains?
You can simply enforce the same case for both strings by using the toLowerCase method for example.
System.assertEquals(true,'ABC'.toLowerCase().contains('a'));
If string contains
String myName = 'John Smith';
If(myName.contains('John')){
System.debug('I am John.');
}
// => I am John.
If string not contains
String myName = 'John Smith';
If(!myName.contains('Sally')){
System.debug('I am NOT Sally.');
}
// => I am NOT Sally.
Share: