因此,例如,我有這樣的字符串:如何從字符串中讀取和刪除數字?
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
,或者如果後面跟着增加值爲dataNo
。說得通?
我該怎麼辦?我怎樣才能讓我的代碼更加靈活?
你嘗試用正則表達式?我不熟悉java,但似乎這可以用正則表達式來完成。 – ldionmarcil
你需要刪除字符串中的每個數字嗎? – dierre
我真的不明白你想要什麼。你可以在這裏發佈一些樣例輸入和輸出嗎?我無法打開該鏈接。 –