On an assignment, I had a string where I wanted to extract a character and store it in another string. It was something like: String s = "12345" ; String part ; part = s.substring( 0, 1 ) ; The above worked. Now, suppose I wish to us charAt() instead of substring()? I tried: String s = "12345" ; String part ; part = s.charAt( 0 ) ; When I compile the above, it errors at assigning a char to a string. So, how do I fix this? Is it more efficient to use charAt() and convert it to a string, or just use substring()? thanks, -Bryan
It's a bit hard to answer this without a bit of context. You indicate that you only want a single character, but you want to store it in a String -- why? If whatever uses this single character can simply be recoded to accept a char rather than a String, that would be the most efficient method. Other than that, the speed difference between String.substring() and makeing a new String from the result of charAt() is probably negligible. What is important, though is how the code makes sense to someone reading it. If (for example) the single character is an important system concept, and will only ever be a single character, using charAt makes that explicit. On the other hand, if in other similar cases it might be more than one character in length, then use substring() to make that explicit. I strongly recommed this approach as a whole. Write all your code first for a human reader/maintainer, and only consider efficiency if it becomes important. A program which doesn't do what anyone wants, and can't be modified to do so, is a pretty useless program. Even if it does what it does very fast indeed.
He wants to take the value of the the single digit and use it to index an array. One way to get a substring and then use Integer.parseInt() to get the value of the first digit. An alternative would involve using the charAt() method. Without spelling out exactly what steps one would take to reach this end, shat would you recommend for this, Frank?