
使用replace方法
该方法的作用是替换字符串中所有指定的字符,然后生成一个新的字符串,例如:
String s = “abcat”;
String s1 = s.replace(‘a’,‘1’);
该代码的作用是将字符串s中所有的字符a替换成字符1,生并慎成的新字符串s1的值是“1bc1t”,而字符串s的内容不发生改变。如果需要将字符串中某个指定的字符串替换为其它字符串,则可以使用replaceAll方法,例如:
String s = “abatbac”;
String s1 = s.replaceAll(“ba”,“12”);
该代码的作用是将字符串s中所有的字符串“ab”替换为“12”,绝搜敬生成新的字符串“a12t12c”,而字符串s的内容漏纳也不发生改变。
字符串在存储上类似字符数组
它每一位单个元素都是能提取的,字符串的零位是它的长度,如s[0]=10,这提供给我们很多方便,例如高精度运算时每一位都能转化为数字存入数组。
通常以串的整体作为 *** 作对象,如:在串中查找某个子串、求取一个子串、在串的某个位置上插入一个子串以及删除一个子串等。两个字符串相等的充要条件是:
长度相等,并且各个对应位置上的字符都相等。设p、q是两个串,求q在p中首次出现的位置的运算叫做模式匹配。串的两种最基本的存储方式是顺序存储方式和链接存储方式。
import java.util.regex.*public 御敬晌class RepTest {
public static void main(String[] args) {
String src 镇锋= ">=,<=,=,>=,<=,=,>=,<=,=,>=,<=,=,>=,<=,=,>=,<=,=,"
System.out.println("原串:"+src)
Matcher ma = Pattern.compile("[^><]=").matcher(src)
while (ma.find()) {
src = src.replaceAll(ma.group(), "")
}
System.out.println("替换:"+src)
//其实还有一个思路,你可以拿逗号切成数组,然后对数组元素进行判稿备断,拿=号切也可以!
}
}
package com.baiduimport java.io.*
public class ReplaceChinese {
public static void main(String[] args) {
String filePath = "F:\\workspace\\onlineChat\\src\\com\\baidu\\ReplaceChinese.java"蚂裂
File file = new File(filePath)
if (!file.exists()) {
System.out.println("文件不存在!")
return
}
BufferedReader reader = null
String result = ""// 用于存修改后的文字蔽衫
String lineString = ""
try {
reader = new BufferedReader(new FileReader(file))
String tempString = null
int line = 1
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
for (int i = 0i <tempString.length()i++) {
if (tempString.substring(i, i + 1).matches(
"[\u4e00-\u9fa5]")) {
lineString += "[您要替换的代码闷并闭]"
} else {
lineString += tempString.substring(i, i + 1)
}
}
result += lineString + "\n"
lineString = ""
line++
}
reader.close()
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("F:\\workspace\\onlineChat\\src\\com\\baidu\\ReplaceChinese1.java")))
bw.write(result)
bw.flush()
bw.close()
} catch (IOException e) {
e.printStackTrace()
} finally {
if (reader != null) {
try {
reader.close()
} catch (IOException e1) {
}
}
}
}
}
由于时间紧迫,只把功能实现了,优化你自己做做,能够成功运行
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)