课时57:其他操作方法
摘要:
- Public String Concat(String str)
- public String intern()
- public String isEmpty()
- public int length()
- public String trim()
- public String toUpperCase()
- public String toLowerCase()
在String类里面还有一些比较小的方法提供给开发者使用,这些方法如下:
NO |
方法名称 |
类型 |
|
01 |
Public String Concat(String str) |
普通 |
描述字符串的连接过程 |
02 |
public String intern() |
普通 |
字符串入池 |
03 |
public String isEmpty() |
普通 |
判断是否为空字符(不是null) |
04 |
public int length() |
普通 |
计算字符串的长度 |
05 |
public String trim() |
普通 |
驱除左右的空格信息 |
06 |
public String toUpperCase() |
普通 |
转大写 |
07 |
public String toLowerCase() |
普通 |
转小写 |
01. Public String Concat(String str)
1.1 作用:描述的就是字符串的连接过程。
1.2 范例:观察字符串的连接
在原有strA的基础上加上代码
System strB = “www.”concat(“mldn”).concat(“.cn”); System.out.println(strA == strB);
进而进行编译并观察结果,从整体的运行结果来讲,虽然内容相同,但是发现最终的结果是一个False,证明此操作并没有实现静态的定义:
02. public String intern()
作用:对字符串进行入池保存
03. public String isEmpty()
3.1 作用:判断是否为空字符串(不是Null)
需要记住的是,在字符串定义的时候“""”和“Null ”不是一个概念,一个表示有实例化对象的,一个表示没有实例化对象,而isEmpty()只要是判断字符串的内容,所以一定要有实例化对象的时候进行调用。
3.2 范例:判断空字符串
如示例,若写成“mldn”.isEmpty
,则运行出来的结果为False。
04. public int length()
4.1作用:计算字符串的长度。
05. public String trim()
5.1 作用:驱除左右的空格信息。
5.2 范例:观察Length()与Trim()
在进行一些数据输入的时候(用户名和密码),用户很难保证输入的数据没有空格,有空格的就必须对输入的数据进行处理,此时应使用Trim()
。
首先只输入str.length:
运行结果为:17
在此基础上加上以下内容:
String trimStr = str.trim() ; System.out.println(str); System.out.println(trimStr); System.out.println(trimStr.length () ); } }
此时的运行结果为:11
此时可以看到,长度减少为14。需要注意的是,Trim ()
并没有消除中间空格的本事。
06. public String toUpperCase()
6.1 作用:转大写。
07. public String toLowerCase()
7.1 作用:转小写。
在String类里面提供有大小写转换,但是这种转换的特征是可以避免非字母的转换。
7.2 范例:观察大小写转换
public class StringDemo { public static void main(String args[]){ string str -"Hello World !!!"; Systen.out.println(str.toUpperCase()); System.out,println(str.toLowerCase()); } }
编译结果为:
可以看到变成结果为全大写和全小写。用这样的方式进行转换可以节约我们的开发成本,毕竟如果我们要自己去写,还需要去判断字母范围,而后在进行转换。
虽然在Java之中String类已经提供有大量的方法,但是缺少了一个字母大写的方法,这个方法可以由开发者自行设计实现,利用方法的组合即可。
范例:自定义一个实现首字母大写的方法:
class StringUtil { public static string initcap(String str) { if (str == null'll "".equals(str)){ return str ; // 原样返回 } if (str.length()= 1){ return str.toUpperCase(); } Returnstr.substring(0,1).toUpperCase()+str.substring(1);} } public class stringDemo { public static void main(String args[]) { System.out,println(StringUtil,initcap("hello")) ; System.out.println (StringUtil.initcap("m")) ; } }
观察运行结果为:
可以观察到,首字母H大写了。此代码是在日后实际开发中必定使用的程序,务必理解。
以上就是这节课其他操作方法的所学内容。