+ 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.