String str="/File/Name.txt"; String msg=str.replaceAll(".",""); 输出msg为什么是空
时间: 2023-07-06 16:43:20 浏览: 46
在 Java 中,replaceAll() 方法使用正则表达式进行字符串替换,而正则表达式中的点号(.)是一个特殊字符,表示匹配任意一个字符。因此,当你使用". "作为参数调用replaceAll()方法时,它会将任何字符都替换为空字符串,导致最终结果为空。如果你想要将字符串中所有的点号都替换成空字符串,应该使用转义字符"\.",这样它就会将点号作为普通字符来处理。所以,正确的代码应该是:
```
String str="/File/Name.txt";
String msg=str.replaceAll("\\.", "");
```
这样,msg 就会成为"/FileName"。
相关问题
android String str = "@@@@@hello world"; String newStr = str.replaceAll("@ ", "")输出newStr
答案应该是:
"@@@@@hello world"
因为你的代码中使用的替换字符串是"@ ",而原始字符串中的"@"后面没有空格,所以不会被替换。如果要替换所有的"@",可以使用如下代码:
```
String str = "@@@@@hello world";
String newStr = str.replaceAll("@+", "");
System.out.println(newStr);
```
这样输出的newStr就是"hello world",所有的"@"都被替换为空字符串了。
import java.io.*; public class TestCopy1 { private static void createStuFile() throws IOException { File file = new File("fin.txt"); FileOutputStream fos = new FileOutputStream(file); String str = "Alcatel provides end-to-end solutions."; byte[] m = str.getBytes(); fos.write(m); fos.close(); } public static void main(String[] args) throws IOException { createStuFile(); File file = new File("fin.txt"); File file2 =new File("fout.txt"); FileReader fr = new FileReader(file); FileWriter fw = new FileWriter(file2); int x = fr.read(); while(x!=-1) { if((char)x==' '||(char)x=='\t') { x=(char)x; x.replaceAll(" +", " "); } System.out.print((char)x); fw.write(x); x = fr.read(); } fr.close(); fw.close(); } }代码改错
代码中有一个错误:在将字符替换为空格时,使用了 `replaceAll()` 方法,但该方法是 String 类的方法,不能直接应用于字符变量。应该改为使用字符常量 `' '` 来表示空格,并使用 `Character.toString()` 方法将其转换为字符串:
```
if ((char) x == ' ' || (char) x == '\t') {
x = ' ';
String space = Character.toString((char) x);
str = str.replaceAll(" +" + space, space);
}
```
另外,代码中的 `fw.write(x)` 应该是 `fw.write((char) x)`,否则写出的是字节而非字符。完整代码如下:
```java
import java.io.*;
public class TestCopy1 {
private static void createStuFile() throws IOException {
File file = new File("fin.txt");
FileOutputStream fos = new FileOutputStream(file);
String str = "Alcatel provides end-to-end solutions.";
byte[] m = str.getBytes();
fos.write(m);
fos.close();
}
public static void main(String[] args) throws IOException {
createStuFile();
File file = new File("fin.txt");
File file2 = new File("fout.txt");
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(file2);
int x = fr.read();
String str = "";
while (x != -1) {
if ((char) x == ' ' || (char) x == '\t') {
x = ' ';
String space = Character.toString((char) x);
str = str.replaceAll(" +" + space, space);
}
str += (char) x;
System.out.print((char) x);
fw.write((char) x);
x = fr.read();
}
System.out.println("\n\n" + str); // 打印替换后的字符串
fr.close();
fw.close();
}
}
```