How to convert/parse from String to char in java?

2019-01-04 16:57发布

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

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

14条回答
男人必须洒脱
2楼-- · 2019-01-04 17:36
 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);
查看更多
神经病院院长
3楼-- · 2019-01-04 17:36
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));
        }
    }
}
查看更多
\"骚年 ilove
4楼-- · 2019-01-04 17:37

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);
查看更多
做个烂人
5楼-- · 2019-01-04 17:37

You can do the following:

String str = "abcd";
char arr[] = new char[len]; // len is the length of the array
arr = str.toCharArray();
查看更多
做个烂人
6楼-- · 2019-01-04 17:40

I may be a little late but I found this useful, understand cadena as String, and left column title as Convert to. :-)

UPDATE: So, I finally got back my password, I updated with copiable text so may others can just copy and paste like always, and for some others that can get indexation of the data (if it does). :-) Happy November Mustache.

Convertion Table

double  --> Double.parseDouble(String);
float   --> Float.parseFloat(String);
long    --> Long.parseLong(String);
int     --> Integer.parseInt(String);
char    --> StringGoesHere.parseFloat(int position);
short   --> Short.parseShort(String);
byte    --> Byte.parseByte(String);
boolean --> Boolean.parseBoolean(String);
查看更多
放荡不羁爱自由
7楼-- · 2019-01-04 17:41

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']
查看更多
登录 后发表回答