当前位置: 首页 > news >正文

java中split() replace() replaceAll()三个函数分析

本文系转载,转自:http://feigme.iteye.com/blog/147259

java.lang.String split


String的split方法是直接按照给定的字符串对字符串进行拆分,例如
    String value = "a,b,c,d,e";
    String[] names = value.split(",");
    for(int i=0,n=names.length;i
    System.out.print(names[i]);
    } 

运行结果:

a b c d e

但是在做ip解析时发现出了问题,代码如下:

    String value = "209.242.1.1";
    String[] names = value.split(".");
    for(int i=0,n=names.length;i
    System.out.print(names[i]+" ");
    } 

理想的输出结果应该是219 242 1 1,结果什么都没有输出。

很奇怪哦。看一下split的方法签名吧。

    public String[] split(String regex) 

这里的参数的名称是regex ,也就是 Regular Expression(正则表达式)。这个参数并不是一个简单的分割用的字符,而是一个正则表达式:

    public String[] split(String regex, int limit) {
    return Pattern.compile(regex).split(this, limit);
    } 

split 的实现直接调用的 Matcher 类的 split 的方法。“. ”在正则表达式中有特殊的含义,因此我们使用的时候必须进行转义。

修改代码如下:

    String value = "209.242.1.1";
    String[] names = value.split("\\.");
    for(int i=0,n=names.length;i
    System.out.print(names[i]+" ");
    } 
Replace 方法

首先看看Replace方法的介绍
    String java.lang.String.replace(char oldChar, char newChar)
    Returns a new string resulting from replacing all occurrences of oldChar in
    this string with newChar.
    If the character oldChar does not occur in the character sequence represented by
    this String object, then a reference to this String object is returned. Otherwise,
    a new String object is created that represents a character sequence identical to
    the character sequence represented by this String object, except that every
    occurrence of oldChar is replaced by an occurrence of newChar.
    Examples:
    "mesquite in your cellar".replace('e', 'o')
    returns "mosquito in your collar"
    "the war of baronets".replace('r', 'y')
    returns "the way of bayonets"
    "sparring with a purple porpoise".replace('p', 't')
    returns "starring with a turtle tortoise"
    "JonL".replace('q', 'x') returns "JonL" (no change)
    Parameters:
    oldChar the old character.
    newChar the new character.
    Returns:
    a string derived from this string by replacing every occurrence of oldChar with newChar.
用法 :
    @Test
    public void testReplace(){
    String A = "aaa bCskd dkkAik kdaFe";
    System.out.println(A.replace('a', '_'));
    }
结果为:___ bCskd dkkAik kd_Fe

此方法用来替换char字符,对字符串不能处理
A.replace('aaa', '=') 是错误的

但是
A.replace(“aaa”, “=”)却是可以的
    @Test
    public void testReplace(){
    String A = "aaa bCskd dkkAik kaaaFe";
    System.out.println(A.replace("aaa", "="));
    }
结果为:= bCskd dkkAik k=Fe

可见 replace("","")与方法replaceAll("","")拥有差不多的功能
仔细看看差别
String java.lang.String.replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence
with the specified literal replacement sequence. The replacement proceeds from
the beginning of the string to the end, for example, replacing "aa" with "b" in
the string "aaa" will result in "ba" rather than "ab".
Parameters:
target The sequence of char values to be replaced
replacement The replacement sequence of char values
Returns:
The resulting string
Throws:
NullPointerException if target or replacement is null.
Since:
1.5
是1.5之后才有的功能哦

但是 replaceAll却更强大
    @Test
    public void testReplace(){
    String A = "aaa bCskd dkkAik kaaaFe";
    System.out.println(A.replace(" ", ""));
    } 
结果为aaabCskddkkAikkaaaFe
replaceAll可以将字符串内部的空格去掉
但是用replace(' ','')方法却不可以
replace(" ","")方法可以

另外一点
    @Test
    public void testReplace(){
    String A = "aaa bCskd dkkAik kaaaFe";
    System.out.println(A.replaceAll("[a-z]", "="));
    } 
结果为:=== =C=== ===A== ====F=
replaceAll可以用正则表达式,强大啊
我们看看replaceAll的用法
java 代码
    String java.lang.String.replaceAll(String regex, String replacement)
    Replaces each substring of this string that matches the given regular expression
    with the given replacement.
    An invocation of this method of the form str.replaceAll(regex, repl) yields exactly
    the same result as the expression
    java.util.regex.Pattern. compile(regex).java.util.regex.Pattern.matcher(java.lang.CharSequence) matcher(str). replaceAll(repl)
    See Also:
    java.util.regex.Pattern
    Parameters:
    regex the regular expression to which this string is to be matched
    Returns:
    The resulting String
    Throws:
    PatternSyntaxException if the regular expression's syntax is invalid
    Since:
    1.4
    @spec
    JSR-51

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • SPOJ-COLONY - Linearian Colony!简单二分思想
  • msfconsole 控制台使用和操作
  • 数据库范式
  • sed awk grep三剑客常用
  • 数据库事务隔离级别
  • 全排序算法
  • 用Spring+Junit4.4进行测试(使用注解)
  • Java HashMap 分析四篇连载
  • Leetcode 144. Binary Tree Preorder Traversal
  • 单页web应用是什么?它又会给传统网站带来哪些好处?
  • 深入理解HTML协议
  • BootStrap学习笔记
  • 深入解析 HTML DocumentType 元素
  • Android -- 获取网络数据并将数据存到本地数据库中
  • CSS选择符
  • JavaScript-如何实现克隆(clone)函数
  • 2018天猫双11|这就是阿里云!不止有新技术,更有温暖的社会力量
  • Android 架构优化~MVP 架构改造
  • AzureCon上微软宣布了哪些容器相关的重磅消息
  • centos安装java运行环境jdk+tomcat
  • CSS3 聊天气泡框以及 inherit、currentColor 关键字
  • css的样式优先级
  • JAVA多线程机制解析-volatilesynchronized
  • MySQL QA
  • Vue2.0 实现互斥
  • Web Storage相关
  • 安卓应用性能调试和优化经验分享
  • 互联网大裁员:Java程序员失工作,焉知不能进ali?
  • 基于 Ueditor 的现代化编辑器 Neditor 1.5.4 发布
  • 使用common-codec进行md5加密
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 一些css基础学习笔记
  • 用 vue 组件自定义 v-model, 实现一个 Tab 组件。
  • - 语言经验 - 《c++的高性能内存管理库tcmalloc和jemalloc》
  • Hibernate主键生成策略及选择
  • 蚂蚁金服CTO程立:真正的技术革命才刚刚开始
  • 说说我为什么看好Spring Cloud Alibaba
  • ​浅谈 Linux 中的 core dump 分析方法
  • ​人工智能书单(数学基础篇)
  • # 详解 JS 中的事件循环、宏/微任务、Primise对象、定时器函数,以及其在工作中的应用和注意事项
  • $GOPATH/go.mod exists but should not goland
  • (3)选择元素——(14)接触DOM元素(Accessing DOM elements)
  • (7)摄像机和云台
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (Java)【深基9.例1】选举学生会
  • (JS基础)String 类型
  • (pojstep1.1.1)poj 1298(直叙式模拟)
  • (二刷)代码随想录第16天|104.二叉树的最大深度 559.n叉树的最大深度● 111.二叉树的最小深度● 222.完全二叉树的节点个数
  • (附表设计)不是我吹!超级全面的权限系统设计方案面世了
  • (附源码)ssm高校运动会管理系统 毕业设计 020419
  • (限时免费)震惊!流落人间的haproxy宝典被找到了!一切玄妙尽在此处!
  • ./configure、make、make install 命令
  • .net 受管制代码
  • .NET 直连SAP HANA数据库