question about charAt function
i know java API function charAt for example
String s="dato"
char r=s.charAt(0); r is equal d
but my question is how realy it works or what function can i use instead of charAt f开发者_如何学Gounction to get same result? thanks
To what purpose? I mean, if charAt(0)
does what you want, why look for something else?
But, to answer your question: no, there is no (reasonably straight forward) way to get the nth character from a String in Java. You could use String
's substring(...)
method, but that returns a String
, not a char
.
Or first convert your String
into an array of char
's with String
'stoCharArray()
and get a character from the array, but that's just silly when you have charAt(...)
at your disposal.
There is no "function", there are only methods on objects, one object class is String
, and this class offers charAt()
for this purpose. Note that a String
is similar to an array of char
s, or a sequence of chars, and retrieving a character is just accessing the correct index in that sequence.
Note that it would be possible to get the first char in other ways (like converting the string to an array or whatever), but that wouldn't really make sense.
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
charAt
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
精彩评论