连接字符串数组+分隔符 [英] joining array of strings + a separator
问题描述
java noob在这里...
java noob here...
这让我发疯了,因为我知道这很简单,但是我已经为此工作了30分钟...
This is driving me nuts because I know it's something so simple but I have been working on this for 30 mins...
这是来自打架游戏
对于参数= [代码",战斗",打开",!"]和分隔符="/",输出应为 myConcat(参数,分隔符)=代码/战斗/打开/!/".
For arguments = ["Code", "Fight", "On", "!"] and separator = "/", the output should be myConcat(arguments, separator) = "Code/Fight/On/!/".
我的代码:
String myConcat(String[] arguments, String separator) {
for(int i = 0; i <= arguments.length; i++){
String output = arguments[0] + separator;
}
return output;
}
错误:第5行上的file.java:错误:找不到符号 返回输出; ^ 符号:变量输出 位置:类_runfniek 1个错误
error: file.java on line 5: error: cannot find symbol return output; ^ symbol: variable output location: class _runfniek 1 error
任何提示将不胜感激...
any tips would be greatly appreciated...
推荐答案
首先,StringBuilder胜于+操作.
First, StringBuilder is prefered than + operation.
第二,在循环主体中定义String输出实际上是不保存值的错误.
Second, it is a mistake to define String output in the loop body which does not save the value actually.
第三,需要考虑边框,即参数数组的最后一个元素不应附加分隔符.
Third, need consider the border, i.e. no separator should be appended for the last element of the argument array.
第四,它是i < arguments.length
,而不是i <= arguments.length
String myConcat(String[] arguments, String separator) {
StringBuilder output = new StringBuilder();
for(int i = 0; i < arguments.length; i++){
output.append(arguments[i]);
if(i < arguments.length-1){
output.append(separator);
}
return output.toString();
}
这篇关于连接字符串数组+分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!