您的位置:首页 > 其它

常用的String类方法

2016-12-11 15:12 260 查看
方法包含在java.lang.String中。String类型一经创建就不可改变。可变的字符串可用StringBuffer类型或者StringBuilder类型。

代码如下:

package Stringpackage;

public class StringFunction {
public static void main(String[] args)
{
String a=new String("abcdefg");
String b=new String("Abcdefg");
String c=new String("a bc");
String d=new String("abcabcabcabc");
//按字典顺序比较两个字符串,返回int值,相等返回0,小于字符串参数返回小于0的值,大于字符串参数返回大于0的值;
System.out.println("The result of a compare to b is "+a.compareTo(b)+"\n"+"The result of b compare to a is "+a.compareTo(c));
System.out.println("----------------------------------");
//按字典顺序比较两个字符串,忽略大小写;
System.out.println("a compare to b ignoring case : "+a.compareToIgnoreCase(b));
System.out.println("----------------------------------");
//将字符串参数连接到字符串的末尾;
System.out.println("connect b to the end of a: "+a.concat(b));
System.out.println("----------------------------------");
// 当且仅当此字符串包含指定的 char 值序列时,返回 true。
System.out.println("tell if a contains appointed String: "+a.contains("bcd"));
System.out.println("----------------------------------");
// 将此字符串与指定的 StringBuffer 或者charsequence比较。
System.out.println("tell if a equals  to a StringBuffer or a charsequence: "+a.contentEquals("abcd"));
System.out.println("----------------------------------");
//测试该字符串是否以指定后缀sffix结束
System.out.println("tell a is end with appointed String: "+"\n"+a.endsWith("efg")+"\n"+a.endsWith("df"));
System.out.println("----------------------------------");
//判断字符串是否为空
System.out.println("tell a is empty"+a.isEmpty());
System.out.println("----------------------------------");
//输出字符串的长度
9825
:
System.out.println("the length of appointed String is: "+c.length());
System.out.println("----------------------------------");
//用指定的子串替换字符串中的特定的子串
System.out.println("the pre d is: "+d+"\n"+"the followed d is: "+d.replace("ab", "ef"));
System.out.println("----------------------------------");

}
}


输出结果为:

The result of a compare to b is 32
The result of b compare to a is 66
----------------------------------
a compare to b ignoring case : 0
----------------------------------
connect b to the end of a: abcdefgAbcdefg
----------------------------------
tell if a contains appointed String: true
----------------------------------
tell if a equals  to a StringBuffer or a charsequence: false
----------------------------------
tell a is end with appointed String:
true
false
----------------------------------
tell a is emptyfalse
----------------------------------
the length of appointed String is: 4
----------------------------------
the pre d is: abcabcabcabc
the followed d is: efcefcefcefc
----------------------------------




全的类介绍参考可参考网站易百
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: