41

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?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Pawan
  • 31,545
  • 102
  • 256
  • 434

6 Answers6

92

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.

Sibbo
  • 3,796
  • 2
  • 23
  • 41
57

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
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • 12
    The only problem with this is the resulting value is a `char` not a `string`. – Luc Apr 14 '17 at 21:46
11

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

String name="123456789";
System.out.println(name.substring(0,1));
Ali Hassan
  • 188
  • 4
  • 8
1

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);

                    }
Paramatma Sharan
  • 437
  • 5
  • 11
-4

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;
Aditya
  • 13
  • 5
-10

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

  • 2
    That is C or C++. In Java, it would work, but only if you cast the string to a char array. For example, like this: `s.toCharArray()[0];` – deLock Sep 01 '18 at 11:50