您的位置:首页 > 其它

String类常用方法3

2018-01-31 14:09 176 查看
转小写与大写操作

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: