Cómo convertir / analizar de String a char en java?


¿Cómo puedo analizar un valor String en Java a un tipo char?

Sé cómo hacerlo a int y double (por ejemplo, Integer.parseInt("123")), ¿Hay una clase para Cadenas y Caracteres?

Author: Eric Leschinski, 2011-10-21

14 answers

Si su cadena contiene exactamente un carácter, la forma más sencilla de convertirlo en un carácter es probablemente llamar al charAt método:

char c = s.charAt(0);
 253
Author: Mark Byers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-21 18:12:06

Puede usar el .charAt (int) función con cadenas para recuperar el valor char en cualquier índice. Si desea convertir la cadena a una matriz char, intente llamar a .toCharArray () en la cadena.

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']
 63
Author: Gaʀʀʏ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-04 15:39:30

Puedes usar este truco:

String s = "p";

char c = s.charAt(0);
 47
Author: Genjuro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-21 18:12:35

Si la cadena tiene 1 carácter, simplemente tome ese carácter. Si la cadena no tiene 1 carácter, no se puede analizar en un carácter.

 8
Author: Vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-21 18:13:04
 String string = "This is Yasir Shabbir ";
 for(char ch : string.toCharArray()){

 }

O si usted quiere individualmente entonces usted puede como

char ch = string.charAt(1);
 5
Author: Yasir Shabbir Choudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-29 12:00:55

Org.apache.común.lang.StringEscapeUtils .(un)métodos EscapeJava son probaby lo que quieres

Respuesta de brainzzy no mía:

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

 4
Author: sinekonata,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:47

Si desea analizar una cadena a un carácter, mientras que el objeto String representa más de un carácter, simplemente use la siguiente expresión: char c = (char) Entero.parseInt (s) . Donde s es igual a la cadena que desea analizar. La mayoría de la gente olvida que los caracteres representan un número de 16 bits, y por lo tanto pueden ser parte de cualquier expresión numérica:)

 3
Author: Adam Martinu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-03 14:55:08

La forma más sencilla de convertir un String a un char es usar 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

Aquí está un guión completo:

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();   
    }
}
 3
Author: Isabella Engineer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-20 09:08:44
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));
        }
    }
}
 2
Author: user6307216,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-08 16:38:11

Puedes hacer lo siguiente:

String str = "abcd";
char arr[] = new char[len]; // len is the length of the array
arr = str.toCharArray();
 1
Author: Santosh Kulkarni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-10 17:04:35

Simplemente puede usar el toCharArray() para convertir una cadena en matriz char:

    Scanner s=new Scanner(System.in);
    System.out.print("Enter some String:");
    String str=s.nextLine();
    char a[]=str.toCharArray();
 1
Author: Abhishek kumar singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-03 15:55:23

Puedo llegar un poco tarde, pero encontré esto útil, entiendo la cadena como Cadena, y el título de la columna izquierda como Convertir a. :-)

Tabla de Conversión

 0
Author: Hikhuj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-31 04:57:17

Una manera de ensayo:

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

Para la salida vea este enlace: Haga clic aquí

Gracias: -)

 0
Author: Shivanandam Sirmarigari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-12 02:11:37

Puede usar el .charAt (int) función con cadenas para recuperar el valor char en cualquier índice. Si desea convertir la cadena a una matriz char, intente llamar a .toCharArray () en la cadena. Si la cadena tiene 1 carácter, simplemente tome ese carácter llamando .charAt (0) (or.First () en C#).

 0
Author: Mayer Sariggs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-25 15:09:00