Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a character in a string by index?

I know that I can return the index of a particular character of a string with the indexof() function, but how can I return the character at a particular index?

like image 765
SmartestVEGA Avatar asked Mar 10 '10 12:03

SmartestVEGA


People also ask

How do you find the character of a string at an index?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

Can you access a string by index?

Strings are ordered sequences of character data, 00:15 and the individual characters of a string can be accessed directly using that numerical index. String indexing in Python is zero-based, so the very first character in the string would have an index of 0 , 00:30 and the next would be 1 , and so on.

How do you find an individual character in a string?

You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

How do you get a character at a given index in a string in python?

Accessing characters by index in string | indexof So characters in string of size n, can be accessed from 0 to n-1. Suppose we have a string i.e. Let's access character at 5th index i.e. We can access and use the character i.e.


2 Answers

string s = "hello"; char c = s[1]; // now c == 'e' 

See also Substring, to return more than one character.

like image 75
Tim Robinson Avatar answered Sep 22 '22 12:09

Tim Robinson


Do you mean like this

int index = 2; string s = "hello"; Console.WriteLine(s[index]); 

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)     Console.WriteLine(c); 
like image 30
Brian Rasmussen Avatar answered Sep 23 '22 12:09

Brian Rasmussen