Java字符串处理

来源:互联网 发布:意式咖啡机推荐知乎 编辑:程序博客网 时间:2024/06/05 19:56

Java字符串替换、截取、拆分



替换方法:



public String replaceAll(String regex,String replacement)普通用新的内容替换掉全部旧的内容public String replaceFirst(String regex,String replacement)普通替换首个满足条件的内容

替换范例:观察替换的结果


public class test1 {public static void main(String[] args) {String str = "helloworld";String resultA = str.replaceAll("l", "_");String resultB = str.replaceFirst("l", "_");System.out.println(resultA); //  he__owor_dSystem.out.println(resultB); //  he_loworld}}

截取方法:(使用了方法重载)

★方法重载详见:http://blog.csdn.net/qq418280718/article/details/69808476

public String substring(int beginIndex)普通从指定位置截取到结束的字符串public String substring(int beginIndex, int endIndex)
普通
从指定位置截取到指定位置的字符串

范例:

public class test1 {public static void main(String[] args) {String str = "helloworld";String resultA = str.substring(5);String resultB = str.substring(0, 5);System.out.println(resultA); //  worldSystem.out.println(resultB); //  hello}}

注意:不能使用负数作为截取的开始点。

拆分方法:

public String[] split(String regex)普通按照制定的字符串进行全部拆分public String split(String regex, int limit)普通按照制定的字符串部分拆分,最后的数组长度
就是按照limit决定的,即前面拆,
后面不拆。

范例:

public class test1 {public static void main(String[] args) {String str = "hello world nihao a";String [] resultA = str.split(" ");//按照空格拆分for(int x = 0; x < resultA.length; x++)System.out.println(resultA[x]);//结果: hello//world//nihao//aString [] resultB = str.split(" ",2);//现在是2for(int x = 0; x < resultB.length; x++)System.out.println(resultB[x]);/*结果 :    helloworld nihao a如果是3,结果就是      hello  world   nihao a*/}}

实验: 我们都知道ip地址是根据“ . ”隔开的,我们可以试一下拆分ip地址试试,试了我们会发现,结果什么都没有,这时候我们可以在字符“ . ”前加个反转义字符' \\ '即变为 ‘ \\. ’ 再次拆分就可以啦!

字符串拆分的重要应用:

看一下下面的代码以及输出:

public class test1 {public static void main(String[] args) {String str = "张三:20|李四:15|王武:25";String []result = str.split("\\|"); //根据'|'拆分for(int x= 0;x < result.length; x++){String []temp = result[x].split(":");//再次拆分System.out.println("姓名:"+temp[0]+",年龄:"+temp[1]);}}}


根据上面的输出可以看到,拆分在我们的开发之中确实很叼的。。。

0 0
原创粉丝点击