我基本上是在记事本中执行“替换”功能,但我无法删除/替换从.txt文件中读取的字符串部分。
我有:“1 = 55.748555 -0.000000 1.210479 0.000000 0”
我想:“1 = 55.748555 -1 1.210479”
虽然我想手动给它-1
由于我在这里引起某种混淆,我的代码在下面。我没有开始更换部件,因为我不知道如何。
package txtzuibl;
import java.io.*;
import java.io.BufferedWriter;
public class Txt_zu_ibl {
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("test.txt");
FileWriter fw = new FileWriter("output.txt");
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
String zeile = "";
int i =0;
zeile ="Closed Index Arclength";
bw.write(zeile);
bw.newLine();
zeile="Begin section ! 1";
bw.write(zeile);
bw.newLine();
zeile=" Begin curve ! 1";
bw.write(zeile);
bw.newLine();
while( zeile != null )
//Some editing on the beginning
{
i++;
System.out.print(i+" ");
//Just for me so I can check if I didn't screw up
System.out.println(zeile);
zeile = br.readLine();
if( i>57 )
{
bw.write(zeile);
bw.newLine();
}
}
bw.close();
br.close();
}
}
答案 0 :(得分:1)
要替换部分字符串,可以使用replace或replaceAll。首先尝试:
String s = "1=55.748555 -0.000000 1.210479 0.000000 0";
s = s.replace( "-0.000000", "-1" );
s = s.replace( "0.000000", "" );
s = s.replace( "0", "" ); // Oh no! this doesn't work because...
这不行,因为它也会在1.210479中杀死零。因此,让我们使用正则表达式:
s = s.replaceAll( "-0.000000\\b", "-1" ); // exactly six decimal places
s = s.replaceAll( "\\b0.000000\\b", "" );
s = s.replaceAll( "\\b0\\b", "" );
最后两个可以合并
s = s.replaceAll( "\\b0(?:.000000)?\\b", "" );
或者,如果小数点后的零可以是任何正数:
s = s.replaceAll( "\\b0(?:.0+)?\\b", "" );
将保留一些空格(从删除的数字之间)。您可以通过另一个折叠多余空间的replaceAll来清理它们:
s = s.replaceAll( "\\s{2,}", " " );