0

I have the following code that wants to capitalize first character of each word.

What I want to do is to make sure both (`john doe' & 'jane doe') first character is capital, if both matches mean first character is capital then return true.

Here is my code:

List<Account> acts = [SELECT Id,Name from ACCOUNT WHERE Name IN ('john doe', 'jane doe');
List<String> names = new List<String>();
for (Integer i = 0; i < names.size(); i++) {
    names = acts[i].Name.split(' ');
    names[i] = names[i].capitalize();
}
name = String.join(names, ' ');
system.debug(name);  

Problem:

When I run the above code it only output the first name like John & Jane instead of first and last name.

0

1 Answer 1

2

This scenario is a good example of why you should define a method to handle a specific concern. In this case:

String titleCase(String input)
{
    List<String> words = input.split('\\s');
    for (Integer i = 0; i < words.size(); i++)
        words[i] = words[i].capitalize();
    return String.join(words, ' ');
}

Then, it would be more clear to manipulate multiple records:

for (Account person : [SELECT Name FROM Account WHERE Name IN ('jane doe', 'john doe'))
    system.debug(titleCase(person.Name));
1
  • 2
    I'd recommend adding curly braces. I know this is just example code, but we should set a good example for future visitors.
    – sfdcfox
    Commented Aug 25, 2017 at 19:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .