2011-07-15 68 views
1

我有一個ArrayStrings從緩衝區字符串中分離出來。現在陣列中的每個項目都有一個{value, offset, count, & hash}。我怎樣才能得到數組中項目的偏移量?獲取字符串的偏移量

實施例:

String buffer = aVeryLongString; 
String[] splitStringArray = buffer.split(regex); 

for(String s: splitStringArray) { 
    // Get the offset of each item 
    // Do something 
} 
+0

您可能想再次分割? – Waldheinz

+0

必須有另一個分隔符來拆分每個元素中的值,偏移量,計數和散列值,我認爲 – ascanio

回答

2
String buffer = aVeryLongString; 
String[] splitStringArray = buffer.split(regex); 

int offset = -1; 
for(String s: splitStringArray) { 
    offset = buffer.indexOf(s, offset + 1); // avoid duplicates 
    System.out.println(offset); 
} 

使用String.indexOf(String str, int offset)可以找出字符串的偏移量。它開始在給定的偏移量處搜索字符串。所以使用前一個字符串的偏移量將解決重複的問題。

+0

感謝您的幫助! –

2

String.indexOf(字符串str)應該工作。

for(String s: splitStringArray) { 
    System.out.println(buffer.indexOf(s)); 
} 
+2

只有在沒有重複時纔會工作,對嗎? – Kal

+1

是的,它會在字符串中得到它的第一個實例。 –

+0

感謝您的幫助! –

2

您可能想使用正則表達式Matcher/Pattern類而不是String.split函數。使用Matcher類,您可以遍歷與find()的匹配,並通過end()獲取當前位置。

+0

我實際上正在重寫我的代碼,不包含正則表達式。從權力口述。 ;) –

+0

但String.split(正則表達式)使用引擎蓋下的Pattern! – pauli

+0

我知道,我知道......哈哈 –

0

String.split()並沒有提供一種方法來恢復這些信息(沒有循環數組並添加以前的長度)。如果你需要這樣的關於結果子字符串的額外信息,你可以試試java.util.Scanner

或者,正如其他海報建議之一,使用java.util.regex類Pattern和Matcher。

0

如果正則表達式總是匹配一個固定長度,那麼該偏移量將是前面字符串的長度加上拆分字符串的長度之和。

但是,如果正則表達式的長度不固定...嗯,不是一個簡單的問題。我想,你必須基本上重複分割用來找到棋子的邏輯。

+0

是的,正則表達式匹配的字符串的長度將是一個可變長度,因爲它正在拾取可以變化的參數。即HTML/CSS顏色代碼。 –

0

說,你想分割一個buffer空白字符。 (\S+代表非空白字符)

String buffer = aVeryLongString; 
Pattern p = Pattern.compile("\\S+"); 
Matcher m = p.matcher(buffer); 

while(m.find()) { 
    String matchStr = m.group(); 
    int startOffset = m.start(); 
    int endOffset = m.end(); 
    System.out.println("[ " + matchStr + " " + Integer.toString(startOffset) + " " + Integer.toString(endOffset) + " ]"); 
} 
相關問題