+ Start a Discussion
Jahnvi JasaniJahnvi Jasani 

how to check for whitespaces in a string or how could I know that the string contains one word or more than one word?

I have taken one input text in visual force page for searching purpose - it searches from the Contact sObject.
Now, if user inputs only a single word then it should search from the FirstName fiels of Contact.
If user inputs 2 words or more than 2 words than it should search first word from FirstName of contact and rest words from the lastName of contacts.

my apex code:
public class AccountsRelatedContactsController {
    string keyword;
    List<Contact> results;   
    String str1;
    String str2;
    public string getkeyword(){
        return keyword;
    public List<Contact> getresults(){
        return results;
    public void setkeyword(string input){
        string[] str = keyword.split(' ',2);   
        system.debug('size of str is = ' + str.size());
    Public PageReference search_new(){        
        results=(List<Contact>)[FIND :str1 IN Name fields Returning Contact(FirstName,LastName)][0];        
        return null;
    public List<Contact> getContacts() {     
        Id accountId = apexpages.currentpage().getparameters().get('id'); 
        System.debug('Account id is = ' + accountId);
            string query='Select Id, FirstName, LastName from Contact where AccountId=:accountId';        
            System.debug('Query result' + query);
            List<Contact> results=Database.query(query);       
            return results;  
            string query='SELECT Id, FirstName,LastName,LastViewedDate FROM Contact WHERE LastViewedDate !=null ORDER BY LastViewedDate DESC limit 10';
            List<Contact> acc=Database.query(query);
            return acc;

my Visualforce page:
<apex:page controller="AccountsRelatedContactsController">
    <apex:form >
        <apex:pageBlock title="Contact List" id="contacts_list">      
            <apex:inputText value="{!keyword}"/>
            <apex:commandButton value="Search" action="{!search_new}"/>
            <apex:pageBlockTable value="{!results}" var="r">
                <apex:column value="{!r.FirstName}"/>
                <apex:column value="{!r.LastName}"/>
            <apex:repeat var="cont" value="{!Contacts}">
                    <apex:outputLink value="/{!cont.ID}" > {!cont.FirstName} {!cont.LastName} </apex:outputLink>

Hi Janvi,

Calculating Total no of words in a string are easy 
String str = 'Foo Bar Force';
List<String> parts = str.split(' ');

If this was helpful don't forget to mark as best answer else let me know your side 

Thank you 
Avaneesh Singh