# 如何在 Java 中将字符串转换为`char`

> 原文： [https://beginnersbook.com/2014/06/how-to-convert-char-to-string-and-a-string-to-char-in-java/](https://beginnersbook.com/2014/06/how-to-convert-char-to-string-and-a-string-to-char-in-java/)

在本教程中，我们将看到`char`到`String`和`String`到`char`转换的程序。

## 将`char`转换为`String`

我们有以下两种方式进行字符串转换。
方法 1：使用`toString()`方法
方法 2：使用[`valueOf()`](https://beginnersbook.com/2013/12/java-string-copyvalueof-method-example/)方法

```java
class CharToStringDemo
{
   public static void main(String args[])
   {
      // Method 1: Using toString() method
      char ch = 'a';
      String str = Character.toString(ch);
      System.out.println("String is: "+str);

      // Method 2: Using valueOf() method
      String str2 = String.valueOf(ch);
      System.out.println("String is: "+str2);
   }
}
```

**输出：**

```java
String is: a
String is: a
```

## 将字符串转换为字符

我们可以使用[`String`类](https://beginnersbook.com/2013/12/java-strings/)的[`charAt()`方法](https://beginnersbook.com/2013/12/java-string-charat-method-example/)将`String`转换为`char`。

```java
class StringToCharDemo
{
   public static void main(String args[])
   {
      // Using charAt() method
      String str = "Hello";
      for(int i=0; i<str.length();i++){
        char ch = str.charAt(i);
        System.out.println("Character at "+i+" Position: "+ch);
      } 
   }
}
```

**输出：**

```java
Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o
```