[英]How to convert char array back to string
There is a code which capitalize first word letter. 有一个将首字母大写的代码。 However I wasn't able to find a method to convert char array back to String: 但是我找不到将char数组转换回String的方法:
For example: "hello world" code transforms it to ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
I want to transform it back to "Hello World" 例如:“ hello world”代码将其转换为["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
我想将其转换回“ Hello World”
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
for (int i = 0; i < chars.length; i++){
if (chars[i] == ' '){
chars[i + 1] = Character.toUpperCase(chars[i + 1]);
}
}
System.out.println(chars);
}
}
String str = String.valueOf( chars );
要么
String str = new String( chars );
Two other remarks: 另外两句话:
In your approach, you should make sure, that the [i+1]
element actually exists. 在您的方法中,应确保[i+1]
元素确实存在。 A String like "Test ", ending with a space, would throw an ArrayIndexOutOfBoundsException
in your code. 像“ Test”这样的字符串(以空格结尾)将在您的代码中引发ArrayIndexOutOfBoundsException
。
You should either close the Reader, or better: use a try-with-resources block like 您应该关闭阅读器,或者更好:使用try-with-resources块,例如
try( BufferedReder reader = new InputStreamReader(System.in) ) { ... } catch( ... ) { ... }
which closes the Reader for you. 这会为您关闭阅读器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.