【问题标题】:split returns a string in place of string arraysplit 返回一个字符串代替字符串数组
【发布时间】:2017-10-09 10:57:31
【问题描述】:

每当我尝试在 java 中读取一个字符串并使用String[] part=str.split(" ") 将其拆分为一个字符串数组时,它都会返回一个数组来代替返回一个字符串数组,即part。 length=1,因此在访问时会发出 ArrayIndexOutOfBoundException

这是我目前正在处理的代码:

import java.io.*;
import java.util.*;
public static void main(String[] args)
{
    InputReader in = new InputReader(System.in);
    String s=in.readString();
    String[] str=s.split(" ");
    for(int i=0;i<str.length;i++)
        System.out.println(str[i]);
}
private static class InputReader
{
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream)
    {
        this.stream = stream;
    }

    public int read()
    {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars)
        {
            curChar = 0;
            try
            {
                numChars = stream.read(buf);
            } catch (IOException e)
            {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-')
        {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do
        {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }
    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }
    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }
    public boolean isSpaceChar(int c)
    {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next()
    {
        return readString();
    }

    public interface SpaceCharFilter
    {
        public boolean isSpaceChar(int ch);
    }
   }
}

例如,每当我写“你好,我在这里”时,它必须在 4 个单独的行中打印“你好”、“我”、“我”和“这里”,理想情况下,它只打印“你好”。

如何解决这个问题?

【问题讨论】:

  • 你的代码请
  • ypu要拆分什么字符串?
  • 请说明它是返回一个字符串,还是一个大小为 1 的字符串数组,其中原始字符串作为数组的唯一元素。
  • 但是 s 里面的值是什么?
  • 我个人不能,工作阻止了 imgur 网站。通常最好将实际信息实际放入,而不是将其放入图片中。

标签: java string split indexoutofboundsexception


【解决方案1】:

readString 方法只是读取一个空格,即下一个单词 - 这里是您代码中的相应部分(这不是解决方案,只需从不起作用的代码中复制和粘贴):

public String readString()
{
    ...  // ignore spaces at start
    do
    {
        res.appendCodePoint(c);
        c = read();
    } while (!isSpaceChar(c));  // STOPS reading if it got a space
    return res.toString();
}

不需要调用 split 因为InputReader 已经在做这项工作了。

但是InputReader 真的需要吗?看看Scanner 类。

【讨论】:

  • 这并不能解决我测试过的他的问题也一直只得到 hello 作为输出
  • @MohammadOghli “那个”什么?我发布的代码只是导致问题的部分(如问题中发布的那样) - 它只是为了显示出了什么问题 - 并且(根据他的评论)似乎(根据他的评论)使用 Sacnner,正如我在最后指出的那样一句话,解决了这个问题!抱歉,在您发现错误之前我发现了错误...
  • @MohammadOghli 我更新了答案以澄清发布的代码只是显示有缺陷部分的原始代码的引用!
【解决方案2】:

您的代码看起来不错,没有问题。我们可以猜测字符串“s”的问题,因为“split”效果很好。 当字符串“s”中没有符号“”时,“str”中将只有一个元素,不要排列。

例如,您可以选择代码来发现您的问题:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFileChooser;

public class ReadFileTxt {

    static File fileName;
    static ArrayList<String[]> data = new ArrayList<String[]>();

    public ReadFileTxt() {
        readFile();
    }

    public static void readFile() {
        String str;
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setVisible(true);
        int result = fileChooser.showOpenDialog(fileChooser);
        if (result == JFileChooser.APPROVE_OPTION) {
            fileName = fileChooser.getSelectedFile();
        }
        try {
            FileReader fr = new FileReader(fileName);
            BufferedReader reader = new BufferedReader(fr);
            str = reader.readLine();
            while (str != null) {

                // Delete redundant blanks
                for (int i = 0; i < str.length(); i++) {
                    str = str.replace("  ", " ");
                }
                String[] strMas = str.split(" ");
                data.add(strMas);
                str = reader.readLine();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ReadFileTxt();
    }
}

它的txt文件:

1                      XXXXXXXX                  12342
2                      YYYYYYY                    45321
3                      ZZZZZZZZZ               5454532

【讨论】:

  • 我已附上截图,请看一下。
  • 由于您的代码,看起来方法“readString()”必须在字符串中转换“in”的上下文。我认为这可能是这里的问题。我需要检查一下
【解决方案3】:

我没有发现你的程序代码有任何问题,我对其进行了测试,它返回的正是你想要的结果

我认为读取字符串s时这行有问题:

String s = in.readLine();

您可以测试这个code 并查看输出:

    Scanner in = new Scanner(System.in);
    String s = in.nextLine();
    String[] str = s.split(" ");
    for(int i = 0; i < str.length; i++){ 
        System.out.println(str[i]);
    }

更新:

我测试了您的InputReader 类方法,发现此方法readString() 存在问题,它只读取行中的单个字符串并忽略空格字符后的所有字符串:

    InputReader in = new InputReader(System.in);
    String s = in.readString();
    System.out.println(s); 

如果您在字符串 "hello I am here" 上测试此代码,它将仅返回 hello,因此您应该使用 readString 方法解决问题以获得正确的输出。

检查此readString() 新实现以解决您的问题,它运行良好:

public String readString()
{
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (c != '\n'); // stop reading at the end of line
        return res.toString();
}

【讨论】:

  • 当我尝试使用扫描仪或缓冲阅读器时,它会给出正确的输出,但是当我使用 FastIO 作为获取输入的方法时,它会给出错误。我什至附上了它的快照以及整个代码。尝试粘贴我的代码并检查您的编辑器。
  • @kunjalrupala 在我更新的答案中检查你的readString() 的新代码实现,它非常适合你的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 2020-08-27
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
相关资源
最近更新 更多