Pawan
Pawan

Reputation: 32321

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

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?

Upvotes: 46

Views: 263083

Answers (7)

blackorbs
blackorbs

Reputation: 625

To return as String:

private String getSymbol(String text){
    return ""+text.charAt(0);
}

Upvotes: 0

Ali Hassan
Ali Hassan

Reputation: 305

The string has a substring method that returns the string at the specified position.

String name="123456789";
System.out.println(name.substring(0,1));

Upvotes: 12

Aditya
Aditya

Reputation: 13

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

Upvotes: -4

Paramatma Sharan
Paramatma Sharan

Reputation: 445

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

Upvotes: 1

PackratDragon
PackratDragon

Reputation: 39

Java strings are simply an array of char. So, char c = s[0] where s is string.

Upvotes: -10

Sibbo
Sibbo

Reputation: 3914

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.

Upvotes: 101

Etienne de Martel
Etienne de Martel

Reputation: 36852

String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.

So, assuming getSymbol() returns a String, to print the first character, you could do:

System.out.println(ld.getSymbol().charAt(0)); // char at index 0

Upvotes: 64

Related Questions