1. Overview
1.概述
String is a common type, and char is a primitive in Java.
String是一个常见的类型,而char是Java中的primitive。
In this tutorial, we’ll explore how to convert a String object to char in Java.
在本教程中,我们将探讨如何在Java中把String对象转换为char。
2. Introduction to the Problem
2.对问题的介绍
We know that a char can only contain one single character. However, a String object can contain multiple characters.
我们知道,一个char只能包含一个单一字符。然而,一个String对象可以包含多个字符。
Therefore, our tutorial will cover two cases:
因此,我们的教程将涵盖两种情况。
- The source is a single-character string.
- The source is a multi-character string.
For case 1, we can get the single character as a char easily. For example, let’s say this is our input:
对于情况1,我们可以很容易地得到作为char的单个字符。例如,我们说这是我们的输入。
String STRING_b = "b";
After the conversion, we expect to have a char ‘b‘.
转换后,我们期望有一个字符’b‘。
For case 2, if the source String is a multi-character string and we still want to get one single char as a result, we must analyze the requirement to pick the desired character, such as the first, the last, or the n-th character.
对于情况2,如果源String是一个多字符的字符串,而我们仍然希望得到一个单一的char作为结果,我们必须分析要求来挑选所需的字符,如第一个、最后一个或第n个字符。
In this tutorial, we’ll address a more general solution. We’ll convert the source String to a char array that holds each character in the string. In this way, we can pick any elements according to the requirement.
在本教程中,我们将讨论一个更通用的解决方案。我们将把源String转换为char数组,该数组持有字符串中的每个字符。通过这种方式,我们可以根据要求挑选任何元素。
We’ll use STRING_Baeldung as the input example:
我们将使用STRING_Baeldung作为输入例子。
String STRING_Baeldung = "Baeldung";
So next, let’s see them in action.
那么接下来,让我们看看他们的行动。
3. Single Character String
3.单一字符串
Java’s String class provides the charAt() to get the n-th character (0-based) from the input string as char. Therefore, we can directly call the method getChar(0) to convert a single character String to a char:
Java的String类提供了charAt()来从输入字符串中获取第n个字符(基于0)作为char。因此,我们可以直接调用getChar(0)方法来将单个字符String转换成char。
assertEquals('b', STRING_b.charAt(0));
However, we should note that if the input is an empty string, the charAt() method call throws StringIndexOutOfBoundsException:
然而,我们应该注意,如果输入是一个空字符串,charAt()方法的调用会抛出StringIndexOutOfBoundsException。
assertThrows(StringIndexOutOfBoundsException.class, () -> "".charAt(0));
Therefore, we should check the input string is not null or empty before we call the charAt() method.
因此,在调用charAt()方法之前,我们应该检查输入字符串是否为空或空。
4. Multiple Characters String
4.多字符字符串
We’ve learned to use charAt(0) to convert a single character String to char. If the input is a multi-character String, and we know exactly which character we want to be converted to a char, we can still use the charAt() method. For example, we can get the fourth character (‘l‘) from the input string “Baeldung“:
我们已经学会了使用charAt(0)来将单个字符String转换为char。如果输入的是一个多字符的String,并且我们确切地知道我们想把哪个字符转换为char,我们仍然可以使用charAt()方法。例如,我们可以从输入字符串”Baeldung“中获得第四个字符(’l‘)。
assertEquals('l', STRING_Baeldung.charAt(3));
Additionally, we can use String.toCharArray() to get a char[] array containing all the characters:
此外,我们可以使用String.toCharArray()来获得一个包含所有字符的char[]数组。
assertArrayEquals(new char[] { 'B', 'a', 'e', 'l', 'd', 'u', 'n', 'g' }, STRING_Baeldung.toCharArray());
It’s worth mentioning that the toCharArray() method also works for empty string inputs. It returns an empty char array as the result:
值得一提的是,toCharArray()方法也适用于空字符串输入。它返回一个空的char数组作为结果。
assertArrayEquals(new char[] {}, "".toCharArray());
Apart from toCharArray(), String.getChars() can extract consecutive characters from the given String to a char array. The method receives four arguments:
除了toCharArray()之外,String.getChars()可以从给定的String中提取连续的字符到一个char数组。该方法接收四个参数。
- srcBegin – the index of the first character in the string to take, inclusive
- srcEnd – the index of the last character in the string to copy, exclusive
- dst – the destination array, which is our result
- dstBegin – the start offset in the destination array. We’ll discuss this with an example.
First, let’s extract “aeld” from the string “Baeldung” and fill it into a predefined char array:
首先,让我们从字符串”Baeldung“中提取”aeld“,并将其填入一个预定义的char数组。
char[] aeld = new char[4];
STRING_Baeldung.getChars(1, 5, aeld, 0);
assertArrayEquals(new char[] { 'a', 'e', 'l', 'd' }, aeld);
As the test above shows, to call getChars(), we should first have a char array to hold the result.
正如上面的测试所示,要调用getChars(),我们首先应该有一个char数组来保存结果。
In the example, we pass 0 for dstBegin when we call getChars(). This is because we’d like the converted result to start from the first element in the array aeld.
在这个例子中,当我们调用getChars()时,我们为dstBegin传递0。这是因为我们希望转换后的结果从数组aeld中的第一个元素开始。
Of course, sometimes, we want the result to overwrite a middle part of the array. Then we can set the dstBegin to the desired value.
当然,有时候,我们希望结果能覆盖数组的中间部分。那么我们可以将dstBegin设置为所需的值。
Next, let’s see another example to convert “aeld” to chars and overwrite the target array from the second (index=1) element:
接下来,让我们看看另一个例子,将”aeld“转换为字符,并从第二个(index=1)元素覆盖目标数组。
char[] anotherArray = new char[] { '#', '#', '#', '#', '#', '#' };
STRING_Baeldung.getChars(1, 5, anotherArray, 1);
assertArrayEquals(new char[] { '#', 'a', 'e', 'l', 'd', '#' }, anotherArray);
So, as we can see, we pass dstBegin=1 to the method and get the expected result.
所以,我们可以看到,我们把dstBegin=1传给方法,得到了预期的结果。
5. Conclusion
5.总结
In this article, we’ve learned how to convert a String to a char in Java.
在这篇文章中,我们已经学习了如何在Java中把String转换为char。
As always, the code used in the article is available over on GitHub.
一如既往,文章中使用的代码可在GitHub上找到。