获取引号之间的字符串
Obtaining a String Between quotations
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class excersie2
{
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException
{
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> titlestwo = new ArrayList<String>();
String path = "C:\Users\T-450s\Desktop\showtimes.txt";
File showtimes = new File(path);
Scanner fileReader = new Scanner(showtimes);
PrintWriter writer = new PrintWriter("C:\Users\T-450s\Desktop\output.txt");
while(fileReader.hasNextLine())
{
titles.add(fileReader.nextLine());
}
String movie = "";
for(String title : titles)
{
movie = title.substring((title.indexOf("\"")+1), title.lastIndexOf("\""));
}
writer.println("\n" + movie);
writer.close();
}
}
读取以下 txt 文件:
Now Showing
Title: "Deadpool"
Duration: 1 hr 48 mins
Title: "Zoolander"
Duration: 1 hr 42 mins
Title: "Kung Fu Panda 3"
Duration: 1 hr 35 mins
and writes a new file containing:
Deadpool
Zoolaner
Kung Fu Panda 3
我该如何实现?我尝试使用子字符串,但每次都出错。
我不确定这是否是您收到的错误,但我认为是,我认为您收到错误是因为子字符串试图找到 " 但在某些行上找不到,因为它没有存在并且会导致错误,所以您可以做的是用 if 语句包围 movie = substring(...
来检查 "title" 是否包含 ",您也可以这样做 if(title.contains(" \""))
应该将 writer.println 放在 for 循环
中
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class excersie2
{
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException
{
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> titlestwo = new ArrayList<String>();
String path = "C:\Users\T-450s\Desktop\showtimes.txt";
File showtimes = new File(path);
Scanner fileReader = new Scanner(showtimes);
PrintWriter writer = new PrintWriter("C:\Users\T-450s\Desktop\output.txt");
while(fileReader.hasNextLine())
{
titles.add(fileReader.nextLine());
}
String movie = "";
for(String title : titles)
{
movie = title.substring((title.indexOf("\"")+1), title.lastIndexOf("\""));
}
writer.println("\n" + movie);
writer.close();
}
}
读取以下 txt 文件:
Now Showing
Title: "Deadpool"
Duration: 1 hr 48 mins
Title: "Zoolander"
Duration: 1 hr 42 mins
Title: "Kung Fu Panda 3"
Duration: 1 hr 35 mins
and writes a new file containing:
Deadpool
Zoolaner
Kung Fu Panda 3
我该如何实现?我尝试使用子字符串,但每次都出错。
我不确定这是否是您收到的错误,但我认为是,我认为您收到错误是因为子字符串试图找到 " 但在某些行上找不到,因为它没有存在并且会导致错误,所以您可以做的是用 if 语句包围 movie = substring(...
来检查 "title" 是否包含 ",您也可以这样做 if(title.contains(" \""))
应该将 writer.println 放在 for 循环