+ 1

If we want to get the last char from string, how can we get it?

string x = "I know C#"; char x = ???????

28th Jul 2016, 3:20 AM
Ricardo Pucca
Ricardo Pucca - avatar
6 ответов
+ 10
char lastCharacter = x[x.length - 1] in your example, you can't give both the string and char variables the same name
28th Jul 2016, 4:58 PM
Tomek Cymes
Tomek Cymes - avatar
+ 6
char getLastChar(string s) { return s[s.Length-1]; }
9th Nov 2016, 8:13 PM
Hadi Akbarzadeh
Hadi Akbarzadeh - avatar
+ 2
char need root like charoot
7th Sep 2016, 3:48 AM
Salad
Salad - avatar
+ 1
Tomek example is right, but we need to think about exception... If string is empty this example will be generate error message.
25th Aug 2016, 1:46 AM
Usepov Oleg Surenovich
Usepov Oleg Surenovich - avatar
+ 1
string x = "I know C#"; char x = str[8]; This example can only be used if you know the exact amount of chars in the string, so as uos mentioned you can delve a little further into other examples to handle exceptions or more robust code.
29th Sep 2016, 1:35 PM
Benzz
0
Look up a character at index method similar to the one in Java. Then pass the parameter variableName.length() as the parameter in the character at method. This will always give the index of the last character in the string.
29th Jul 2016, 6:05 AM
nk361
nk361 - avatar