一、Sring类的去空格和分割功能
去除字符串连段空格:
String trim()
按照指定符号份额字符串
String[] split(String str)
代码块:
public class StringDemo{
public static void main(String[] str){
String s1 = "helloword";
String s2 = " helloword ";
String s3 = " hello word ";
System.out.println("--"+s1+"--");//--helloword--
System.out.println("--"+s1.trim()+"--");//--helloword--
System.out.println("--"+s2+"--");//-- helloword --
System.out.println("--"+s2.trim()+"--");//--helloword--
System.out.println("--"+s3+"--");//-- hello word --
System.out.println("--"+s3.trim()+"--");//--hello word--
//String[] split(String str)
//创建字符窜对象
String s4 = "aa,bb,cc";
String[] strArray = s4.split(",");
for(int x=0;x<strArray.length;x++){
System.out.println("strArray[x]");
//aa
//bb
//cc
}
}
}
二、字符串练习------数据元素按格式拼接
分析:
1、定义一个int型数组
2、方法实现:将数组中的元素按照指定的格式拼接成一个字符串
3、调用方法
4、输出结果
代码块
public class StringTest{
public static void mian(String[] str){
int arr[] = {1,2,3};
String s = arrayToString(arr);
System.out.pirnln("s:"+s);
}
/*
两个明确
1、返回值类型:String
2、参数列表: int[] arr
*/
public static String arrayToString(int[] arr){
s+="[";
for(int x=0;x<arr.length;x++){
if(x==arr.length-1){
s+=arr[x];
}else{
s+=arr[x];
s+=",";
}
}s+="]"
}
}
输出结果:
【1,2,3】