+ Start a Discussion
grandmastergrandmaster 

How to read a string

Hi

 

Say I have a string, as below:

 

String str = "Great";

 

Now I want to find out what is the character at the first position, second position and so on... How do I do that?

 

I basically need to find out what is the character at the second position of the word "Great", which is "r".

 

This might be simple but cant seem to get it work. In other languages it is easy but in Apex, I wasnt able to find out the trick.

 

It would be great if someone can help with some code sample.

 

Thanks

M

Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

Not great, but this should do it 

 

 

String str = 'Great';
integer j = 1;
for(integer i =0; i< str.length(); i++)
System.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ' + str.substring(i,j++));

 

All Answers

Ritesh AswaneyRitesh Aswaney

Not great, but this should do it 

 

 

String str = 'Great';
integer j = 1;
for(integer i =0; i< str.length(); i++)
System.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ' + str.substring(i,j++));

 

This was selected as the best answer
MiddhaMiddha

 

String str = 'Great';
pattern myPattern = pattern.compile('{0}');
system.debug('\n\n== ' + myPattern.split(str)[2]);