Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get only the first character of a String?

Tags:

java

char

I have a for loop in Java.

for (Legform ld : data) {     System.out.println(ld.getSymbol()); } 

The output of the above for loop is

Pad

CaD

CaD

CaD

Now my question is it possible to get only the first characer of the string instead of the whole thing Pad or CaD

For example if it's Pad I need only the first letter, that is P
For example if it's CaD I need only the first letter, that is C

Is this possible?

like image 540
Pawan Avatar asked Nov 03 '11 19:11

Pawan


People also ask

How do you extract the first character of a string?

To get the first and last characters of a string, use the charAt() method, e.g. str. charAt(0) returns the first character, whereas str. charAt(str. length - 1) returns the last character of the string.

How do I get the first character of a string in Java?

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 get the first character of each word in a string?

To get the first letter of each word in a string: Call the split() method on the string to get an array containing the words in the string. Call the map() method to iterate over the array and return the first letter of each word. Join the array of first letters into a string, using the join() method.

How do you get the first character of a string in Python?

String Indexing Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.


1 Answers

Use ld.charAt(0). It will return the first char of the String.

With ld.substring(0, 1), you can get the first character as String.

like image 108
Sibbo Avatar answered Sep 20 '22 08:09

Sibbo