在 Java 中,如何将 String 转换为 char 或将 char 转换为 String?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2429228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java how does one turn a String into a char or a char into a String?
提问by David
Is there a way to turn a char
into a String
or a String
with one letter into a char
(like how you can turn an int
into a double
and a double
into an int
)? (please link to the relevant documentation if you can).
有没有办法把 achar
变成 aString
或 aString
用一个字母变成 a char
(就像你如何把 anint
变成 adouble
和 adouble
变成 an int
)?(如果可以,请链接到相关文档)。
How do I go about finding something like this that I'm only vaguely aware of in the documentation?
我如何去寻找这样的东西,我只是在文档中模糊地知道?
采纳答案by polygenelubricants
char firstLetter = someString.charAt(0);
String oneLetter = String.valueOf(someChar);
You find the documentation by identifying the classes likely to be involved. Here, candidates are java.lang.String
and java.lang.Character
.
您可以通过识别可能涉及的类来查找文档。在这里,候选人是java.lang.String
和java.lang.Character
。
You should start by familiarizing yourself with:
您应该首先熟悉:
- Primitive wrappers in
java.lang
- Java Collection framework in
java.util
- 原始包装器
java.lang
- Java Collection 框架中的
java.util
It also helps to get introduced to the API more slowly through tutorials.
它还有助于通过教程更缓慢地介绍 API。
回答by BryanD
String.valueOf('X')
will create you a String "X"
String.valueOf('X')
将为您创建一个字符串 "X"
"X".charAt(0)
will give you the character 'X'
"X".charAt(0)
会给你性格 'X'
回答by Roman
I like to do something like this:
我喜欢做这样的事情:
String oneLetter = "" + someChar;
回答by fastcodejava
String someString = "" + c;
char c = someString.charAt(0);
回答by helpermethod
As no one has mentioned, another way to create a String out of a single char:
正如没有人提到的,另一种从单个字符创建字符串的方法:
String s = Character.toString('X');
Returns a String object representing the specified char. The result is a string of length 1 consisting solely of the specified char.
返回表示指定字符的 String 对象。结果是长度为 1 的字符串,仅由指定的字符组成。
回答by MyUserQuestion
String g = "line";
//string to char
char c = g.charAt(0);
char[] c_arr = g.toCharArray();
//char to string
char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
//(or iterate the charArray and append each character to str -> str+=charArray[i])
//or String s= new String(chararray);
//或 String s= new String(chararray);
回答by Santosh Kulkarni
In order to convert string to char
为了将字符串转换为字符
String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();