Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the nth character of a string?

Tags:

I have a string,

char* str = "HELLO"

If I wanted to get just the E from that how would I do that?

like image 838
Aspyn Avatar asked Dec 10 '11 03:12

Aspyn


People also ask

What is nth character?

To get the nth character in a string, simply call charAt(n) on a String , where n is the index of the character you would like to retrieve. NOTE: index n is starting at 0 , so the first element is at n=0.


2 Answers

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

like image 65
Rei Miyasaka Avatar answered Oct 01 '22 16:10

Rei Miyasaka


You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

like image 27
Graham Perks Avatar answered Oct 01 '22 15:10

Graham Perks