Java字符串String小笔记
菜鸟有话说
String 类代表字符串。Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。String 类包括的方法可用于检查序列的单个字符、比较字符串、搜索字符串、提取子字符串、创建字符串副本并将所有字符全部转换为大写或小写
一、String格式
String a = "我爱你中国";
String b = new Srting();
b = "我爱你中国";
// 以下代码创建了两个字符串
String c = new String("我爱你中国");
char [] d = {'b','o','y'};
String e =new String(date);
char [] d = {'b','o','y'};
String f = new String(d,0,2); //从d中的第一个元素开始取两个
二、String函数
1.长度------length()
用于返回字符串的长度。空字符串的长度返回 0。
String Test = "我爱你中国";
int len = Test.length(); //返回整数类型 len=5
2.比较------equals()||compareTo()
String的比较有equals与compareTO两种方式。
equals的效率高些,compareTo其实就是按照编码的数值求差值,根据差值进行比较,它能确定两个String在字典顺序上的前后性,当你只是想知道是否一致时,用equals也行,效果一样。
String Test1 = "我爱你中国";
String Test2 = "我爱你中国";
String Test3 = "我爱你我爱你";
boolean bol = Test1.equals(Test2); // bol = true;
int result1 = Test1.compareTo(Test2); // result1 = 0;
int result2 = Test2.compareTo(Test3); // result2 = -5092;
equals返回的是boolean类型,非真即假。
compareTo返回的是int类型。当result1=0时,表示test1与test2的值相等,当result=-5092是表示Test3数值比Test2大。
3.开头------startsWith()
用于检测字符串是否以指定的前缀开始。
String Test = "我爱你中国";
boolean bol1 =Test.startsWith("我"); // bol1 = true;
boolean bol2 =Test.startsWith("我爱"); // bol2 = true;
boolean bol3 =Test.startsWith("爱你"); // bol3 = false;
4.结尾------endsWith()
用于测试字符串是否以指定的后缀结束。
String Test = "我爱你中国";
boolean bol1 =Test.endsWith("国"); // bol1 = true;
boolean bol2 =Test.endsWith("中国"); // bol2 = true;
boolean bol3 =Test.endsWith("你中"); // bol3 = false;
5.检索------indexOf()||lastIndexOf()
indexOf(): 返回指定字符在字符串中第一次出现处的位置,如果此字符串中没有这样的字符,则返回 -1。
lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的位置,如果此字符串中没有这样的字符,则返回 -1。
String Test = "我爱你中国'爱你中国'爱你中国";
int wz=Test.indexOf("中国"); //wz=3
int wz=Test.indexOf("中",4); //从4开始(包含4) wz=8
int lastwz=Test.lastIndexOf("中"); //lastwz=13
int lastwz=Test.lastIndexOf("中",10); //到10结束(包含10) lastwz=8
6.截取------substring()
返回字符串的某一子字符串。
String Test = "我爱你中国'爱你中国'爱你中国";
String newTest =Test.substring(3); //从3开始保留后面
//newTest="中国'爱你中国'爱你中国";
String newTest =Test.substring(5,11); //截取从5(保留)开始到11(不包括)结束
//newTest="'爱你中国'";
7.替换------replace()
通过用新字符替换字符串中出现的所有需要替换的字符,并返回替换后的新字符串。
String Test = "我爱你中国'爱你中国'爱你中国";
String newTest =Test .replace("中国", "河南");
//newTest="我爱你河南'爱你河南'爱你河南";
8.分割------split()
根据匹配给定的正则表达式来拆分字符串。
String Test = "张三@李四@王五";
String [] str=b.split("@"); //保留除@以外的每个字符
//str[0]="张三";
//str[1]="李四";
//str[2]="王五";
9.大小写—toUpperCase()||toLowerCase()
toUpperCase() 方法将字符串小写字符转换为大写。
toLowerCase() 方法将字符串转换为小写。
String Test = "abcdefg";
String TEST=Test.toUpperCase(); //TEST="ABCDEFG";
String Test=TEST.toLowerCase(); //Test="abcdefg";
10.空格------trim()
用于删除字符串的空白符。
String Test1 = " abcdefg ";
String Test2 = Test1.trim(); //Test2="abcdefg";