java新手:字符串数组、字符数组和字符串之间的转换

(1)字符串和字符数组的转化

// 字符串转化成字符数组
  String str = "abcdefg";
  char[] ch = str.toCharArray();
  //输出a
  System.out.println(ch[0]);
  //字符数组转化成字符串
  String  strs = new String(ch);

(2)字符串和字符串数组的转化

// 字符串转化成字符串数组
  String str = "hello world";
  //根据空格把字符串隔开
  String[] array = str.split(" ");
  //输出hello
  System.out.println(array[0]);
 
  //字符串数组转化成字符串,只能通过循环
  //StringBuffer主要侧重于对字符串的变化
  StringBuffer sb= new StringBuffer();
  for(int i=0;i<array.length;i++){
       sb.append(str[i]);//追加内容到sb的末尾
  }
  String s = sb.toString();

比较基础,适用于编程新手。

猜你喜欢

转载自blog.csdn.net/w_e_i_1201/article/details/82785137