【发布时间】:2015-12-10 18:50:50
【问题描述】:
例如,我有这个字符串:
0no1no2yes3yes4yes
这里的第一个 0 应该被删除并使用数组的索引。我是通过以下声明这样做的:
string = string.replaceFirst(dataLine.substring(0, 1), "");
但是,当我说出这个字符串时:
10yes11no12yes13yes14no
我的代码失败了,因为我想处理10,但我的代码只提取了1。
所以在排序中,单个数字可以正常工作,但两位或三位数会导致 IndexOutOfBound 错误。
这是代码:http://pastebin.com/uspYp1FK
这里有一些示例数据:http://pastebin.com/kTQx5WrJ
这是示例数据的输出:
Enter filename: test.txt
Data before cleanUp: {"assignmentID":"2CCYEPLSP75KTVG8PTFALQES19DXRA","workerID":"AGMJL8K9OMU64","start":1359575990087,"end":"","elapsedTime":"","itemIndex":0,"responses":[{"jokeIndex":0,"response":"no"},{"jokeIndex":1,"response":"no"},{"jokeIndex":2,"response":"yes"},{"jokeIndex":3,"response":"yes"},{"jokeIndex":4,"response":"yes"}],"mturk":"yes"},
Data after cleanUp: 0no1no2yes3yes4yes
Data before cleanUp: {"assignmentID":"2118D8J3VE7W013Z4273QCKAGJOYID","workerID":"A2P0GYVEKGM8HF","start":1359576154789,"end":"","elapsedTime":"","itemIndex":3,"responses":[{"jokeIndex":15,"response":"no"},{"jokeIndex":16,"response":"no"},{"jokeIndex":17,"response":"no"},{"jokeIndex":18,"response":"no"},{"jokeIndex":19,"response":"no"}],"mturk":"yes"},
Data after cleanUp: 15no16no17no18no19no
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1907)
at jokes.main(jokes.java:34)
基本上,代码应该做的是将数据剥离为如上所示的字符串,然后读取数字,如果后面跟着yes,则增加它在dataYes中的索引值,或者如果后面跟着no 增加 dataNo 的值。有意义吗?
我能做什么?如何让我的代码更灵活?
【问题讨论】:
-
你尝试过正则表达式吗?我不熟悉java,但似乎可以用正则表达式来完成。
-
是否需要删除字符串中的每个数字?
-
我不太明白你想要什么。您可以在这里发布一些示例输入和输出吗?我打不开那个链接。
-
你没有很清楚地解释你想要发生的事情。尝试提供有关您希望如何更改输入的更多信息。
-
@idionmarcii:使用正则表达式检查后如何使用数字?