怎么把一个字符串数组变为一个字符串?
String[] str = {"我","爱","你","中","国"};
除了用Stringbuffer之外 还有什么方法可以吧上面的数组直接变为:
String str1 = "我爱你中国";
------解决方案--------------------String[] str = {"我","爱","你","中","国"};
String result=org.apache.commons.lang.StringUtils.join(str);
------解决方案--------------------String[] str = {"我","爱","你","中","国"};
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length; i++)
{
sb. append(str[i]);
}
String s = sb.toString();
要不是String的数组,char啥的用构造函数就行
------解决方案--------------------public class StringTest {
public static void main(String[] args) {
String[] str={"我","爱","你","中","国"};
changePrint(str);
}
//将一个字符串数组直接以字符串的形式输出
public static void changePrint(String[] value){
//动态添加字符串
StringBuilder sb=new StringBuilder("");
for (int i = 0; i < value.length; i++) {
sb.append(value[i]);
}
System.out.println(sb.toString());
}
}
------解决方案--------------------你也可以直接使用String类库中的方法,将字符串数组转化成单个的字符串输出。程序代码如下
public class StringTest {
public static void main(String[] args) {
String[] str={"我","爱","你","中","国"};
directionPrint(str);
}
//将字符串数组转化成单个字符串直接输出
public static void directionPrint(String[] value){
for (int i = 0; i < value.length; i++) {
System.out.print(value[i].toCharArray());
}
}
}
------解决方案--------------------可以用String.format,仅是一种凑数的解决方法
public static void main(String[] args){
String[] str = {"我","爱","你","中","国"};
final String FORMAT = "%s";
String format = "";
for(int i = 0;i < str.length;++i) {
format += FORMAT;
}
String str1 = String.format(format, str);
System.out.println(str1);
}
------解决方案--------------------
这个方法是可行的,起始看内部的该方法的实现,还是通过循环遍历进行拼接:
public static String join(Object array[])
{
return join(array, ((String) (null)));
}
public static String join(Object array[], String separator)
{
if(array == null)
return null;