查找包含字符串的Java文件的首尾单词
根据题目要求,我们需要找到给定字符串的首尾单词。
让我们探索这篇文章,看看如何使用Java编程语言来实现。
为您展示一些示例
示例1
假设有一个字符串:“Java 是一种众所周知的、高级的、基于类的面向对象编程语言,由Sun Microsystems创建并于1995年首次发布。目前由Oracle拥有,超过30亿台设备运行Java。”
打印该字符串的首尾单词,即“Java”和“Oracle”。
示例2
假设有一个字符串:“为了创建他们的桌面、网络和移动应用程序,所有的大公司都在积极寻求招聘Java程序员。”
打印该字符串的首尾单词,即“For”和“programmers”。
示例3
假设有一个字符串:“我们假设读者对编程环境有一定的了解。”
打印该字符串的首尾单词,即“we”和“environments”。
算法
步骤1 - 创建BufferedReader类的对象。
步骤2 - 使用indexOf()方法查找第一个空格(“ ”)的索引。然后使用substring()方法查找第一个单词。在substring方法中,0和第一个空格索引分别作为起始和结束索引。
步骤3 - 同样,使用indexOf()方法查找最后一个空格(“ ”)的索引。然后使用substring()方法查找最后一个单词。substring()方法(" ")+1 将给出最后一个单词。
步骤4 - 最后,您将看到结果打印在控制台上。
语法
为了获得给定字符串中第一个字符的索引,我们使用indexOf()方法。如果不存在,则返回-1。
以下是它的语法:
int indexOf(char ch)
其中,“ch”指的是您需要其索引位置的特定字符。
为了使用索引值从给定字符串中提取子字符串,我们使用String类的内置substring()方法。
以下是它的语法:
str.substring(int startIndex); str.substring(int startIndex, int endIndex);
其中,startIndex是包含的,endIndex是不包含的。
多种方法
我们提供了多种解决方案。
使用indexOf()和substring()方法
让我们逐一查看程序及其输出。
方法:使用indexOf()和substring()方法
示例
在这种方法中,使用上述算法查找文件中内容的首尾单词。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("E:\file1.txt"))) {
String str;
while ((str = br.readLine()) != null) {
System.out.println("Content of the txt file:");
System.out.println(str);
int firstSpacePosition = str.indexOf(" ");
//get the first word
String firstWord = str.substring(0,firstSpacePosition);
//get the last word
String lastWord = str.substring(str.lastIndexOf(" ")+1);
//print the output of the program
System.out.println("first word : "+firstWord);
System.out.println("Last word: "+lastWord);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
Content of the txt file: Java is a well-known high-level, class-based object-oriented programming language that Sun Microsystems created and first distributed in 1995. Over 3 billion devices run Java, which is currently owned by Oracle first word : Java Last word: Oracle
在本文中,我们探讨了如何在Java中查找包含字符串的文件的首尾单词。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP