Java:将字符转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1829421/
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
Java: Converting a char to a string
提问by Abs
I have just done this in eclipse:
我刚刚在 eclipse 中做到了这一点:
String firstInput = removeSpaces(myIn.readLine());
String first = new String(firstInput.charAt(0));
However, eclipse complains that:
但是,eclipse 抱怨说:
The constructor String(char) is undefined
构造函数 String(char) 未定义
How do I convert a char to a string then??
那么如何将字符转换为字符串?
Thanks
谢谢
EDIT
编辑
I tried the substring method but it didn't work for some reason but gandalf's way works for me just fine! Very straightforward!
我尝试了 substring 方法,但由于某种原因它不起作用,但是 gandalf 的方法对我来说很好用!很直接!
回答by Gandalf
Easiest way?
最简单的方法?
String x = 'c'+"";
or of course
或者当然
String.valueOf('c');
回答by Amber
Instead of...
代替...
String first = new String(firstInput.charAt(0));
you could use...
你可以用...
String first = firstInput.substring(0,1);
substring(begin,end)gives you a segment of a string - in this case, 1 character.
substring(begin,end)为您提供一段字符串 - 在本例中为 1 个字符。
回答by karoberts
Why not use substring?
为什么不使用子字符串?
String first = firstInput.substring(0, 1);
回答by haffax
String x = String.valueOf('c');`
That's the most straight forward way.
这是最直接的方式。
回答by Alexander Pogrebnyak
String firstInput = removeSpaces(myIn.readLine());
String first = firstInput.substring(0,1);
This has an advantage that no new storage is allocated.
这具有不分配新存储空间的优点。
回答by Jon
You could do this:
你可以这样做:
String s = Character.toString('k');

