string
java 字符替换 replace
String src = new String("ab43a2c43d");
System.out.println(src.replace("3","f"));=>ab4f2c4fd.
System.out.println(src.replace('3','f'));=>ab4f2c4fd.
System.out.println(src.replaceAll("\\d","f"));=>abffafcffd.
replace的参数是char和CharSequence,即可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列的意思,说白了也就是字符串);
2)replaceAll的参数是regex,即基于正则表达式的替换,比如,可以通过replaceAll("\\d", "*")把一个字符串所有的数字字符都换成星号;
相同点:
都是全部替换,即把源字符串中的某一字符或字符串全部换成指定的字符或字符串,如果只想替换第一次出现的,可以使用replaceFirst(),这个方法也是基于规则表达式的替换,但与replaceAll()不同的是,只替换第一次出现的字符串;
/*
* Copyright (c) 2018-2025, god-king All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the god.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: god-king (1830278686@qq.com)
*/
package com.king.god.admin;
import org.junit.Test;
/**
* @author god-king
*/
public class GodAdminApplicationTest {
@Test
public void test() {
String df="2";
String[] sdf=df.split(",");
for (String s : sdf) {
System.out.println(s);
}
}
}
切割
public static void main(String[] args){
String s = "my String is s";
boolean result1 = s.contains("my name");
boolean result2 = s.contains("my is");
boolean result3 = s.contains("my String");
System.out.println("result1 is "+result1+"; result2 is "+result2+"; result3 is "+result3);
}
结果:result1 is false;
result2 is false;
result3 is true
含有完全的字符串时才返回true。
“当且仅当此字符串包含指定的 char 值序列时,返回 true”即对于指定的字符串要完全匹配,不可以有额外的字符。