逐行读取而不是逐字读取 [英] Reading File by line instead of word by word

查看:109
本文介绍了逐行读取而不是逐字读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一些代码来扫描输入文件中的回文,但是它从每个字中取出字符串,而不是每行。一个例子是赛车将显示为racecar =回文,或者hot hot to hoot = palindrome,而不是回文,hot =不是回文等。

<这里是我正在做的读取文件目前

  File inputFile = new File(c:/ temp / palindromes 。文本 ); 
扫描仪inputScanner =新扫描仪(inputFile);
while(inputScanner.hasNext())
{
dirtyString = inputScanner.next();

String cleanString = dirtyString.replaceAll([^ a-zA-Z] +,);

int length = cleanString.length();
int我,开始,结束,中间;

begin = 0;
end = length - 1;
middle =(begin + end)/ 2;
$ b $ for(i = begin; i <= middle; i ++){
if(cleanString.charAt(begin)== cleanString.charAt(end)){
begin ++ ;
end--;
}
else {
break;




$ div class =h2_lin>解决方案

您需要做以下更改

更改

  while(inputScanner.hasNext())//这将检查下一个标记。 



dirtyString = inputScanner.next(); //这将读取下一个标记值。

  while(inputScanner.hasNextLine())//这将检查下一行。 

和dirtyString = inputScanner.nextLine(); //这将读取下一行的值。

inputScanner.next()将读取下一个标记

inputScanner.nextLine()将读取一行。


I'm trying to write some code that scans for palindromes in an input file, but it gets strings from each word instead of each line. An example would be racecar would show up as racecar= palindrome or too hot to hoot = palindrome but instead it will go too= not a palindrome, hot= not a palindrome etc.

Here is what I am doing to read the file currently

File inputFile = new File( "c:/temp/palindromes.txt" );
Scanner inputScanner = new Scanner( inputFile );
while (inputScanner.hasNext())
{
    dirtyString = inputScanner.next();

    String cleanString = dirtyString.replaceAll("[^a-zA-Z]+", "");

    int length  = cleanString.length();
    int i, begin, end, middle;

    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;

    for (i = begin; i <= middle; i++) {
        if (cleanString.charAt(begin) == cleanString.charAt(end)) {
            begin++;
            end--;
        }
        else {
            break;
        }
    }
}

解决方案

You need to do the following changes

change

while (inputScanner.hasNext()) // This will check the next token.

and 

dirtyString  = inputScanner.next(); // This will read the next token value.

to

while (inputScanner.hasNextLine()) // This will check the next line.

and dirtyString = inputScanner.nextLine(); // This will read the next line value.

inputScanner.next() will read the next token

inputScanner.nextLine() will read a single line.

这篇关于逐行读取而不是逐字读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆