Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the first character of a String without using any API method

Tags:

java

string

Recently I was being asked this question in an interview:

Find the first character of a String without using any method from String class

Gave the following approaches, assuming str as a String:

  1. str.charAt(0)
  2. str.toCharArray()[0]
  3. str.substring(0,1)

Can anyone suggest me the way it can be achieved?

like image 225
Amit Bhati Avatar asked Feb 05 '16 21:02

Amit Bhati


People also ask

How do I find the first character of a string?

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 .

How do you read the first character of a string in Java?

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.

How do I retrieve the first 5 characters from a string?

string str = (yourStringVariable + " "). Substring(0,5). Trim();


1 Answers

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"
    }
}
like image 166
Tunaki Avatar answered Sep 30 '22 06:09

Tunaki