The cutting function of the String class

String cutting function of the String class

package MyString;
/*
 * 去除字符串两端空格	
 *		String trim()
 * 按照指定符号分割字符串	
 *		String[] split(String str)
 */
public class StringDemo2 {
    
    
	public static void main(String[] args) {
    
    
		//创建字符串对象
		String s1 = "helloworld";
		String s2 = "  helloworld  ";
		String s3 = "  hello  world  ";
		System.out.println("---"+s1+"---");
		System.out.println("---"+s1.trim()+"---");
		System.out.println("---"+s2+"---");
		System.out.println("---"+s2.trim()+"---");
		System.out.println("---"+s3+"---");
		System.out.println("---"+s3.trim()+"---");
		System.out.println("-------------------");
                                                               
		//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]);
		}
	}
}

Concatenate array data into a string practice

package MyString;
/*
   练习:
 * 把数组中的数据按照指定个格式拼接成一个字符串
 * 举例:int[] arr = {1,2,3};
 * 输出结果:[1, 2, 3]
 *
 * 分析:1.定义一个int类型的数组
 *      2.写一个方法实现将数组中的元素按照指定格式拼接一个字符串
 *      3.调用方法、输出结果
 */
public class StringQiege {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    1,2,3};
        String s=arrToString(arr);
        System.out.println("s:"+s);

    }
    public static String arrToString(int[] arr){
    
    
        String s="";
        s+="[";
        for (int i=0;i<arr.length;i++){
    
    
            if (i==arr.length-1){
    
    
                s+=arr[i];
            }else{
    
    
                s+=arr[i];
                s+=",";
            }
        }
        s+="]"; 
        return s;
    }
}

Guess you like

Origin blog.csdn.net/m0_52646273/article/details/114817975