The examples you gave are incorrect.
Since you were using containsIgnoreCase()
, the case is (unsurprisingly) ignored. Since "Coordinator" does, in fact, contain "coo", the containsIgnoreCase()
method is rightly returning true
.
String.contains()
, on the other hand, is case-sensitive
You can run the following snippet to verify
String s1 = 'COO';
String s2 = 'Coordinator';
system.debug(s1.containsIgnoreCase(s2)); // displays false, since the entirety of "Coordinator"
// is not contained in the string "COO"
system.debug(s2.containsIgnoreCase(s1)); // displays true, since "COO" is found at the start
// of "Coordinator" (when case is ignored)
system.debug(s1.contains(s2)); // false
system.debug(s2.contains(s1)); // This one is false this time because contains()
// is case-sensitive ("COO" != "Coo")
I agree with Aidan in that case-sensitivity isn't necessarily the best way to approach this problem.
Given that we're working with job titles here, we probably don't need to dive into RegEx. While you will see some oddball titles here and there, I believe job titles are fairly standardized. A simple string equality check should be sufficient here.
system.debug(s1 == 'COO'); // Returns true, because normal string equality is case-insensitive
If you need to expand this (e.g. I want to separate COO, CFO, CEO, Comptroller, Janitor, and put everyone else into the same bucket), then I'd suggest using a map to avoid a chain of if-else (or a switch).
// Declare a map, and initialize it to contain the target buckets
Map<String, List<Contact>> employeeBucketsMap = new Map<String, List<Contact>>{
'coo' => new List<Contact>(),
'cfo' => new List<Contact>(),
'janitor' => new List<Contact>(),
'others' => new List<Contact>()
};
for(Contact c :contacts){
// The contains() method of a set, and containsKey() for a map _is_ case-sensitive
// so we need to do some pre-processing
String title = c.Title.toLowerCase();
String bucket;
// (condition) ? (expression if true) : (expression if false) is a ternary operator
// Equivalent to an if-else, but perhaps a little shorter to write
employeeBucketsMap.containsKey(title) ? bucket = title : bucket = 'others';
employeeBucketsMap.get(bucket).add(c);
}
containsIgnoreCase()
, is behaving correctly. That is, it is ignoring the case of the letters in the comparison. Since 'coordinator' starts with 'coo', it returns true. Perhaps you mean to usecontains()
instead.String.contains()
was, in fact, case-sensitive. I suppose I'll write a proper answer now, though.