Convert char to String in Java – 在Java中把char转换为String

最后修改: 2016年 8月 30日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

Converting char to String instances is a very common operation. In this article, we will show multiple ways of tackling this situation.

将char转换为String实例是一个非常常见的操作。在这篇文章中,我们将展示处理这种情况的多种方法。

2. String.valueOf()

2.String.valueOf()

The String class has a static method valueOf() that is designed for this particular use case. Here you can see it in action:

String类有一个静态方法valueOf(),是为这个特殊的使用情况而设计的。在这里你可以看到它的作用。

@Test
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
    char givenChar = 'x';

    String result = String.valueOf(givenChar);

    assertThat(result).isEqualTo("x");
}

3. Character.toString()

3.Character.toString()

The Character class has a dedicated static toString() method. Here you can see it in action:

字符类有一个专门的静态toString()方法。在这里你可以看到它的作用。

@Test
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() {
    char givenChar = 'x';

    String result = Character.toString(givenChar);

    assertThat(result).isEqualTo("x");
}

4. Character’s Constructor

4.角色的构造器

You could also instantiate Character object and use a standard toString() method:

你也可以实例化Character对象并使用标准的toString()方法。

@Test
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString() {
    char givenChar = 'x';

    String result = new Character(givenChar).toString();

    assertThat(result).isEqualTo("x");
}

5. Implicit Cast to String Type

5.隐式转换为字符串类型

Another approach is to take advantage of widening conversion via type casting:

另一种方法是通过类型铸造来利用拓宽转换的优势。

@Test
public void givenChar_whenConcatenated_shouldConvertToString() {
    char givenChar = 'x';

    String result = givenChar + "";

    assertThat(result).isEqualTo("x");
}

6. String.format()

6.String.format()

Finally, you can use the String.format() method:

最后,你可以使用String.format()方法。

@Test
public void givenChar_whenFormated_shouldConvertToString() {
    char givenChar = 'x';

    String result = String.format("%c", givenChar);

    assertThat(result).isEqualTo("x");
}

7. Conclusion

7.结论

In this article, we explored multiple ways of converting char instances to String instances.

在这篇文章中,我们探讨了将char实例转换为String实例的多种方法。

All code examples can be found in the GitHub repository.

所有的代码实例都可以在GitHub资源库中找到。