如何在java中将字符串转换/解析为字符?

发布于 2024-12-11 01:06:07 字数 139 浏览 0 评论 0原文

在 Java 中,如何将 String 值解析为 char 类型?

我知道如何对 int 和 double 进行处理(例如 Integer.parseInt("123"))。 有字符串和字符类吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

聆听风音 2024-12-18 01:06:07

如果您的字符串仅包含一个字符,将其转换为字符的最简单方法可能是调用 charAt 方法:

char c = s.charAt(0);

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);
鼻尖触碰 2024-12-18 01:06:07

您可以使用 .charAt(int ) 函数与字符串一起检索任意索引处的 char 值。如果要将 String 转换为 char 数组,请尝试调用 .toCharArray()

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']

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']
哭了丶谁疼 2024-12-18 01:06:07

你可以使用这个技巧:

String s = "p";

char c = s.charAt(0);

you can use this trick :

String s = "p";

char c = s.charAt(0);
纸伞微斜 2024-12-18 01:06:07

我发现这很有用:

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

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);
予囚 2024-12-18 01:06:07

如果字符串长度为 1 个字符,则只需

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.

§普罗旺斯的薰衣草 2024-12-18 01:06:07
 String string = "This is Yasir Shabbir ";
 for(char ch : string.toCharArray()){

 }

或者如果您想要单独的那么您可以

char ch = string.charAt(1);
 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);
无力看清 2024-12-18 01:06:07

org. apache.commons.lang.StringEscapeUtils.(un)EscapeJava 方法可能就是您想要的

答案来自 Brainzzy 不是我的:

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

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

Answer from brainzzy not mine :

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

只有一腔孤勇 2024-12-18 01:06:07

String 转换为 char 的最简单方法是使用 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

这是一个完整的脚本:

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

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();   
    }
}
忆梦 2024-12-18 01:06:07

如果要将 String 解析为 char,而 String 对象代表多个字符,则只需使用以下表达式:
char c = (char) Integer.parseInt(s)
其中 s 等于您要解析的字符串。大多数人忘记了 char 代表 16 位数字,因此可以成为任何数字表达式的一部分:)

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

你好,陌生人 2024-12-18 01:06:07
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));
        }
    }
}
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));
        }
    }
}
坠似风落 2024-12-18 01:06:07

您可以执行以下操作:

String str = "abcd";
char arr[] = new char[len]; // len is the length of the array
arr = str.toCharArray();

You can do the following:

String str = "abcd";
char arr[] = new char[len]; // len is the length of the array
arr = str.toCharArray();
紧拥背影 2024-12-18 01:06:07

您可以简单地使用 toCharArray() 将字符串转换为字符数组:

    Scanner s=new Scanner(System.in);
    System.out.print("Enter some String:");
    String str=s.nextLine();
    char a[]=str.toCharArray();

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();
三生殊途 2024-12-18 01:06:07

论文方式:

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

有关输出,请参阅此链接:单击此处

谢谢:- )

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

嗼ふ静 2024-12-18 01:06:07

您可以使用 .charAt( int) 函数与字符串一起检索任意索引处的 char 值。如果要将 String 转换为 char 数组,请尝试调用 .toCharArray()。如果字符串长度为 1 个字符,只需调用 .charAt(0)(或 C# 中的 .First())即可获取该字符。

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#).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文