function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TinkuTinku 

syntax for Contains(string)

am writing a code, where i need to compare the name which contains some specific letters. what is the syntax for it?

 

Account acc;

(if acc.Name Contains 'ABC')

{

}

 

 

Cory CowgillCory Cowgill

Use the indexOf method on String.

 

public with sharing class TestApex123
{
    static testMethod void testStringContainsTrue()
    {
        Account account = new Account();
        account.Name = 'This is a Test Name';
        String testString = 'Test';
        if(account.Name != null && account.Name.indexOf(testString) != -1)
        {
            system.assert(true);
        }
    }
    
    static testMethod void testStringContainsFalse()
    {
        Account account = new Account();
        account.Name = 'This is a Test Name';
        String testString = 'NOTVALID';
        if(account.Name != null && account.Name.indexOf(testString) == -1)
        {
            system.assert(true);
        }        
    }
}

bob_buzzardbob_buzzard

Actually Apex strings do have a contains method, unlike a lot of programming languages.  You use it like so:

 

 

Boolean result=myString.contains('FORCE');

 

and it returns true if the sequence of characters appears in the String.  

 

 

 

TinkuTinku

Thank you.

 

It worked. :-)

Sitanshu TripathiSitanshu Tripathi
for (Account newAccount: lstAccount) {
        if(!newAccount.Name.Contains('ABC'))
        {
            newAccount.Name = newAccount.Name +' '+ 'ABCD';
        }
    }

Please mark as best answer, if valuable for you.
Don Juan HernandesDon Juan Hernandes
What about if I want only 100% of the word, and not contains? for example - TEST is what I'm looking for, but BITEST, which contains TEST, is NOT what I'm looking for... So basically what I need is contains as a whole word. 
 
KiranKCKiranKC
@Don Juan Hernandes

You can use == to check the exact/100% match. For example,
if('BITEST' == 'BITEST') // or whatever varaible you have defined the other substring on.