gpt4 book ai didi

Java:从文本文件中从特殊单词开始的字符串中获取子字符串

转载 作者:行者123 更新时间:2023-12-01 18:57:37 24 4
gpt4 key购买 nike

我想从文本文件中提取姓名和年龄。有人可以给我一些帮助吗?

文字内容:

fhsdgjfsdk;snfd fsd ;lknf;ksld sldkfj lk 
Name: Max Pain
Age: 99 Years
and they df;ml dk fdj,nbfdlkn ......

代码:

package myclass;

import java.io.*;

public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file = new File("C:\\Users\\Ss\\Desktop\\s.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st.substring(st.lastIndexOf("Name:")));
// System.out.println(st);
}
}

最佳答案

请尝试下面的代码。

public static void main(String[] args)throws Exception 
{
File file = new File("/root/test.txt");

BufferedReader br = new BufferedReader(new FileReader(file));

String st;
while ((st = br.readLine()) != null) {

if(st.lastIndexOf("Name:") >= 0 || st.lastIndexOf("Age:") >= 0) {
System.out.println(st.substring(st.lastIndexOf(":")+1));
}
}
}

关于Java:从文本文件中从特殊单词开始的字符串中获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com