如何使用IndexOf和substring Java从字符串中提取多个单词?

时间:2015-11-03 02:08:13

标签: java string substring indexof

我有一个通过系统导入的文件,现在我卡住了。使用while循环和if语句,并且没有Split()方法的帮助,我怎么能首先读取文件,逐行扫描器?然后我怎么能一个接一个地拉出这些单词,因为我拉出一个单词,一个变量,countWords必须增加一个,说一个字符串中有5个单词,我需要通过循环5次并且countWords将成为5。 这是我到目前为止的代码,有点糟糕。

import java.util.Scanner;
import java.io.*;

class Assignmentfive
{
private static final String String = null;

 public static void main(String[] args) throws              FileNotFoundException
 {
 Scanner scan = new Scanner(new File("asgn5data.txt"));

int educationLevel = 0;
String fileRead = "";
int wordCount = 0;

while (scan.hasNext() && !fileRead.contains("."))
{
  fileRead = scan.nextLine();

  int index = fileRead.indexOf(" ");
  String strA = fileRead.substring(index);

  System.out.print(strA);
  wordCount++;

 }

我的代码还有更多内容,但只有一些计算被注释掉了。 谢谢!

1 个答案:

答案 0 :(得分:1)

以下是重构while (scan.hasNext()) { int wordCount = 0; int numChars = 0; fileRead = scan.nextLine(); // Note: I add an extra space at the end of the input sentence // so that the while loop will pick up on the last word. if (fileRead.charAt(fileRead.length() - 1) == '.') { fileRead = fileRead.substring(0, fileRead.length() - 1) + " "; } else { fileRead = fileRead + " "; } int index = fileRead.indexOf(" "); do { String strA = fileRead.substring(0, index); System.out.print(strA + " "); fileRead = fileRead.substring(index+1, fileRead.length()); index = fileRead.indexOf(" "); wordCount++; numChars += strA.length(); } while (index != -1); // here is your computation. if (wordCount > 0) { double result = (double)numChars / wordCount; // average length of words result = Math.pow(result, 2.0); // square the average result = wordCount * result; // multiply by number of words System.out.println(result); // output this number } } 循环以正确提取,打印和计算句子中所有单词的方法:

fileRead

我通过将字符串The cat is black.硬编码为您的第一个句子The cat is black 来测试此代码。我得到了以下输出。

<强>输出:

ws = ActiveWorkbook.Sheets(i)