简体   繁体   中英

Getting a char from a String

I have a String variable named List .I want to get the first char of the String which is in the List . The problem is, that I cannot use the charAt() function on the List . Here is my effort so far:

List<String> testList = new ArrayList<>();

testList.get(3).chatAt(0) ;

The code you have given should work (apart from the typo). It retrieves the 4th item in the list, which we know is a String because have defined the list as a list of Strings, and then gets the first character of that String. It will obviously break if there are not 4 things in the list, or if the String doesn't have any characters in it.

List<String> testList = new ArrayList<>();
testList.get(3).charAt(0);

You can make things a bit clearer by declaring the String as a variable before you call charAt on it.

String s = testList.get(3);
char c = s.charAt(0);

Methods get(String s) is not available for arrays in Java, probably you confused it with methods of Java Collection Framework (list). If you have an array of string you must first access on the element with array[i] and after call the method charAt(int index) . Finally you must use array[i].charAt(index) where i is the position in the array to the string that you search and index the index of character you must search in the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM