Recently I was being asked this question in an interview:
Find the first character of a
String
without using any method fromString
class
Gave the following approaches, assuming str
as a String:
str.charAt(0)
str.toCharArray()[0]
str.substring(0,1)
Can anyone suggest me the way it can be achieved?
The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .
To get first character from String in Java, use String. charAt() method. Call charAt() method on the string and pass zero 0 as argument. charAt(0) returns the first character from this string.
string str = (yourStringVariable + " "). Substring(0,5). Trim();
Using Matcher
API (and not String
): we create a pattern that captures every character but only find the first one and print it (the dotall mode is enabled to handle the case where the first character is a line separator).
public static void main(String[] args) {
Matcher matcher = Pattern.compile("(.)", Pattern.DOTALL).matcher("foobar");
if (matcher.find()) {
System.out.println(matcher.group(1)); // prints "f"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With