7.8.10其他操作方法

本文深入讲解了Java中字符串的各种操作方法,包括连接(concat)、判断空字符串(isEmpty)、计算长度(length)、去除空格(trim)、大小写转换(toUpperCase/toLowerCase)等。通过实例演示了如何使用这些方法,以及它们在实际应用中的注意事项。

实现长度计算、空字符串判断、大小写转换操作。
其他操作方法

public String concat(String str){普通方法}描述的就是字符串的连接
public String intern(){普通方法}字符串入池
public boolean isEmpty(){普通方法}判断是否为空字符串(是否null)
public int length(){普通方法}计算字符串的长度
public String trim(){普通方法}去除左右的空格信息
public String toUpperCase(){普通方法}字符串内容转大写
public String toLowerCase(){普通方法}字符内容转小写

范例:字符串连接

public class StringDemo15701 {
       public static void main(String[] args) {
		String strA="www.baidu";
		String strB=strA.concat(".com");
		System.out.println(strB);
		System.out.println(strA==strB);//地址比较
	}
}
www.baidu.com
false

concat()的操作形式与“+”类似,但需要注意的事,concat()方法在每一次进行字符串连接后都会返回一个新的实例化对象,属于运行时常量,所以与静态字符串常量的内存地址不同。
在字符串定义的时候,“ " ”和null不是一个概念,一个表示有实例化对象,一个表示没有实例化对象,二isEmpty()主要是判断字符串的内容,所以一定要在有实例化对象的时候调用。
范例:判断空字符串

public class StringDemo15702 {
       public static void main(String[] args) {
		String str="";
		System.out.println(str.isEmpty());//ture内容为空字符串
		System.out.println("lilei".isEmpty());//false内容不是空字符串
	}
}
true
false

范例:观察length()与trim()方法

public class StringDemo15801 {
        public static void main(String[] args) {
			String str=" java.se ";
			System.out.println(str.length());
			String strA=str.trim();
			System.out.println(str);
			System.out.println(strA);
			System.out.println(strA.length());
		}
}
9
 java.se 
java.se
7

String 中取得字符串长度使用的是length()方法,只要是方法后面都会有“()”;而数组中length()方法,只有length属性。

范例:大小写转换

public class StringDemo15802 {
        public static void main(String[] args) {
			String str="www.baidu.com";
			System.out.println(str.toUpperCase());//转大写
			System.out.println(str.toLowerCase());//转小写
		}
}

WWW.BAIDU.COM
www.baidu.com

范例:实现首字母大写功能

public class StringUtil {               //定义一个String工具类
      public static String initcap(String str) {
    	  if(str==null||"".equals(str)) {   //如果传递进来的是空字符串
    		  return str;                   //原样返回
    	  }
    	  if(str.length()==1) {              //判断字符串长度
    		  return str.toUpperCase();      //一个字母直接转大写
    	  }
    	  return str.substring(0,1).toUpperCase()+str.substring(1);//截取首字母转大写后在连接后续字母
      }
      
}


public class StringUtil01 {
       public static void main(String[] args) {
		System.out.println(StringUtil.initcap("java.lilei"));
		System.out.println(StringUtil.initcap("j"));
	}
}

Java.lilei
J
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值