Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.charAt(x) or string[x]?

Is there any reason I should use string.charAt(x) instead of the bracket notation string[x]?

like image 735
Blender Avatar asked May 09 '11 23:05

Blender


People also ask

Can you use charAt for string?

Java String charAt() MethodThe charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

Does charAt return char or string?

charAt(), like the name implies, returns a char, not a string.

What is use of charAt () method?

The charAt() method returns the character at a specified index (position) in a string. The index of the first character is 0, the second 1, ...

What is the meaning of charAt i )-' 0?

charAt(i) will return a character and string. charAt(i)- '0' will return the actual integer value. For e.g. string="12345",this method will return an integer array [1,2,3,4,5].


1 Answers

Bracket notation now works on all major browsers, except for IE7 and below.

// Bracket Notation "Test String1"[6]  // charAt Implementation "Test String1".charAt(6) 

It used to be a bad idea to use brackets, for these reasons (Source):

This notation does not work in IE7. The first code snippet will return undefined in IE7. If you happen to use the bracket notation for strings all over your code and you want to migrate to .charAt(pos), this is a real pain: Brackets are used all over your code and there's no easy way to detect if that's for a string or an array/object.

You can't set the character using this notation. As there is no warning of any kind, this is really confusing and frustrating. If you were using the .charAt(pos) function, you would not have been tempted to do it.

like image 108
Brian Webster Avatar answered Oct 05 '22 09:10

Brian Webster