String类常用方法3

转小写与大写操作

public class StringDemo {
	public static void main(String args[]) {
		String str = "(*(*Hello(*(*" ;		// 定义字符串
		System.out.println(str.toUpperCase()) ;	// 转大写后输出
		System.out.println(str.toLowerCase()) ;	// 转小写后输出
	}
}
程序执行结果:

(*(*HELLO(*(*(“System.out.println(str.toUpperCase())”语句执行结果)

(*(*hello(*(*(“System.out.println(str.toLowerCase())”语句执行结果)


去掉左右空格

public class StringDemo {
	public static void main(String args[]) {
		String str = "   hello   world  ";	// 定义字符串,包含空格
		System.out.println("【" + str + "】");// 原始字符串
		System.out.println("【" + str.trim() + "】");// 去掉空格后的字符串
	}
}

程序执行结果:

  hello   world 

hello   world


取得字符串长度

public class StringDemo {
	public static void main(String args[]) {
		String str = "helloworld";	// 定义字符串
		System.out.println(str.length());// 取得字符串长度
	}
}

程序执行结果:  10


判断是否为空字符串

public class StringDemo {
	public static void main(String args[]) {
		String str = "helloworld";		// 定义字符串
		System.out.println(str.isEmpty()); 	// 判断字符串对象的内容是否为空字符串(不是null)
		System.out.println("".isEmpty());	 // 判断字符串常量的内容是否为空字符串(不是null)
	}
}

程序执行结果:

false(“System.out.println(str.isEmpty())”语句执行结果)

true(“System.out.println("".isEmpty())”语句执行结果)


实现首字母大写的操作

public class StringDemo {
	public static void main(String args[]) {
		String str = "yootk";	// 定义字符串
		System.out.println(initcap(str));// 调用initcap()方法
	}
	/**
	 * 实现首字母大写的操作
	 *  temp 要转换的字符串数据
	 *  将首字母大写后返回
	 */
	public static String initcap(String temp) {
		// 利用substring(0,1)取出字符串的第一位而后将其大写,再连接剩余的字符串
		return temp.substring(0, 1).toUpperCase() + temp.substring(1);
	}
}

程序执行结果:  Yootk







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值