235

How do I parse a String value to a char type, in Java?

I know how to do it to int and double (for example Integer.parseInt("123")). Is there a class for Strings and Chars?

KeyMaker00
  • 6,194
  • 2
  • 50
  • 49
Ren
  • 4,594
  • 9
  • 33
  • 61

14 Answers14

334

If your string contains exactly one character the simplest way to convert it to a character is probably to call the charAt method:

char c = s.charAt(0);
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
75

You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String.

String g = "line";
char c = g.charAt(0);  // returns 'l'
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['l','i','n','e']
Gaʀʀʏ
  • 4,372
  • 3
  • 39
  • 59
  • Well, true, although I was seeking to convert a single character in a string, I guess that could work too. – Ren Oct 21 '11 at 18:16
48

you can use this trick :

String s = "p";

char c = s.charAt(0);
Genjuro
  • 7,405
  • 7
  • 41
  • 61
  • But that will turn `"123"` into `'1'`, is that what you're after? – aioobe Oct 21 '11 at 18:19
  • 1
    I didn't mean to specifically use "123". I was just using as an example. For char it would be a different example like "p" since a char is a single character, not multiple ones. – Ren Oct 21 '11 at 18:42
  • 1
    the toCharArray() function returns an array of chars in case you want to split your string into chars – Genjuro May 07 '13 at 08:27
14

I found this useful:

double  --> Double.parseDouble(String);
float   --> Float.parseFloat(String);
long    --> Long.parseLong(String);
int     --> Integer.parseInt(String);
char    --> stringGoesHere.charAt(int position);
short   --> Short.parseShort(String);
byte    --> Byte.parseByte(String);
boolean --> Boolean.parseBoolean(String);
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Hikhuj
  • 177
  • 1
  • 5
  • 4
    Why thumbs down? This really answer the question, so as you can check how to parse in other types – Davide May 05 '18 at 15:35
  • 4
    @Davide Probably because posts should't include the important information as image when it can be posted as text. Images can't be searched and copy/pasted, are often blocked and can't be read by users relying on screen readers. – Modus Tollens May 05 '18 at 15:46
  • Please **[edit]** your post and show the actual text instead of screenshots. Others can't copy and paste from your images. [See here](https://meta.stackoverflow.com/a/285557/1402846) for details. Thank you. – Pang Jun 12 '18 at 02:29
  • 3
    I agree with @Davide question - "Why thumbs down?". I believe that this will make the user that got this not to contribute with stackoverflow in the future and I believe that this should not be the case. From my perspective "thumbs down" should not ever be used! It's negative in its essence and doesn't bring any value at all. – Marco Aug 28 '18 at 10:45
  • 1
    Are you sure that `char --> StringGoesHere.parseFloat(int position);` is correct? Honestly I haven't checked, but I'm fairly sure `String` doesn't have a `parseFloat` method, and even if it does, I can't see why that would be what you'd be trying to do there. – BeUndead Mar 18 '19 at 01:59
9

If the string is 1 character long, just take that character. If the string is not 1 character long, it cannot be parsed into a character.

Vlad
  • 35,022
  • 6
  • 77
  • 199
5
 String string = "This is Yasir Shabbir ";
 for(char ch : string.toCharArray()){

 }

or If you want individually then you can as

char ch = string.charAt(1);
Yasir Shabbir Choudhary
  • 2,458
  • 2
  • 27
  • 31
4

The simplest way to convert a String to a char is using charAt():

String stringAns="hello";
char charAns=stringAns.charAt(0);//Gives You 'h'
char charAns=stringAns.charAt(1);//Gives You 'e'
char charAns=stringAns.charAt(2);//Gives You 'l'
char charAns=stringAns.charAt(3);//Gives You 'l'
char charAns=stringAns.charAt(4);//Gives You 'o'
char charAns=stringAns.charAt(5);//Gives You:: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

Here is a full script:

import java.util.Scanner;

class demo {
    String accNo,name,fatherName,motherName;
    int age;
    static double rate=0.25;
    static double balance=1000;
    Scanner scanString=new Scanner(System.in);
    Scanner scanNum=new Scanner(System.in);

    void input()
    {
        System.out.print("Account Number:");
        accNo=scanString.nextLine();
        System.out.print("Name:");
        name=scanString.nextLine();
        System.out.print("Father's Name:");
        fatherName=scanString.nextLine();
        System.out.print("Mother's Name:");
        motherName=scanString.nextLine();
        System.out.print("Age:");
        age=scanNum.nextInt();
        System.out.println();
    }

    void withdraw() {
        System.out.print("How Much:");
        double withdraw=scanNum.nextDouble();
        balance=balance-withdraw;
        if(balance<1000)
        {
            System.out.println("Invalid Data Entry\n Balance below Rs 1000 not allowed");
            System.exit(0);
        }       
    }

    void deposit() {
        System.out.print("How Much:");
        double deposit=scanNum.nextDouble();
        balance=balance+deposit;
    }

    void display() {
        System.out.println("Your  Balnce:Rs "+balance);
    }

    void oneYear() {
        System.out.println("After one year:");
        balance+=balance*rate*0.01;
    }

    public static void main(String args[]) {
        demo d1=new demo();
        d1.input();
        d1.display();
        while(true) {//Withdraw/Deposit
            System.out.println("Withdraw/Deposit Press W/D:");
            String reply1= ((d1.scanString.nextLine()).toLowerCase()).trim();
            char reply=reply1.charAt(0);
            if(reply=='w') {
                d1.withdraw();
            }
            else if(reply=='d') {
                d1.deposit();
            }
            else {
                System.out.println("Invalid Entry");
            }
            //More Manipulation 
            System.out.println("Want More Manipulations: Y/N:");
            String manipulation1= ((d1.scanString.nextLine()).toLowerCase()).trim();

            char manipulation=manipulation1.charAt(0);
            System.out.println(manipulation);

            if(manipulation=='y') { }
            else if(manipulation=='n') {
                break;
            }
            else {
                System.out.println("Invalid Entry");
                break;
            }
        }   

        d1.oneYear();
        d1.display();   
    }
}
Vinz
  • 5,997
  • 1
  • 31
  • 52
Isabella Engineer
  • 3,733
  • 1
  • 15
  • 6
4

org.apache.commons.lang.StringEscapeUtils.(un)EscapeJava methods are probaby what you want

Answer from brainzzy not mine :

https://stackoverflow.com/a/8736043/1130448

Community
  • 1
  • 1
sinekonata
  • 364
  • 3
  • 11
3

If you want to parse a String to a char, whereas the String object represent more than one character, you just simply use the following expression: char c = (char) Integer.parseInt(s). Where s equals the String you want to parse. Most people forget that char's represent a 16-bit number, and thus can be a part of any numerical expression :)

Adam Martinu
  • 253
  • 1
  • 11
  • 1
    This is wrong. Parsing a string to a number means that the number was converted to a string, and we want to get the number back. Exactly the same way, parsing a character from a string means that the character was converted to a string, and we want the character back. Using an intermediate number is not what the OP asked about. – Vlad Dec 14 '15 at 14:38
  • @Vlad He did ask for a number, because that's what a `char` is, just like `int` and `double`. He even gave the example `String` "123". and who says you can't convert a `char` to a `String` with a length larger than one, and back? Try it yourself with `char c = 123` : `String.valueOf((int) c).equals("123")` returns `true`. – Adam Martinu Dec 14 '15 at 18:12
  • 1
    Sorry, but everything boils down to the numbers, that's not the point of the question. You can have a look at the accepted answer, which clearly excludes an intermediate `int`. For your example, you needed to **cast** to `int`, which means that you are working not with the original `char`, but with an `int`, which happens to somehow correspond to the original `char`. – Vlad Dec 14 '15 at 18:23
2
import java.io.*;
class ss1 
{
    public static void main(String args[]) 
    {
        String a = new String("sample");
        System.out.println("Result: ");
        for(int i=0;i<a.length();i++)
        {
            System.out.println(a.charAt(i));
        }
    }
}
1

You can do the following:

String str = "abcd";
char arr[] = new char[len]; // len is the length of the array
arr = str.toCharArray();
sswierczek
  • 810
  • 1
  • 12
  • 19
  • You can shorten this to a oneliner `String str = "abc"; char[] char_str = str.toCharArray();` – otaku Dec 03 '17 at 14:11
1

You can simply use the toCharArray() to convert a string to char array:

    Scanner s=new Scanner(System.in);
    System.out.print("Enter some String:");
    String str=s.nextLine();
    char a[]=str.toCharArray();
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
0

You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String. If the string is 1 character long, just take that character by calling .charAt(0) (or .First() in C#).

Rahul
  • 3,293
  • 2
  • 31
  • 43
Mayer Spitz
  • 2,577
  • 1
  • 20
  • 26
0

An Essay way :

public class CharToInt{  
public static void main(String[] poo){  
String ss="toyota";
for(int i=0;i<ss.length();i++)
  {
     char c = ss.charAt(i); 
    // int a=c;  
     System.out.println(c); } } 
} 

For Output see this link: Click here

Thanks :-)

Py-Coder
  • 2,024
  • 1
  • 22
  • 28