2010-11-16 172 views
2

有沒有人有任何想法如何找到分隔符(分隔符)可以是單個字符或幾個字符的分隔字符串中的第n個字段(字符串)。查找分隔字符串中的第n個字符串

例如,

string = "one*two*three" 

separator = "*" 

和用戶定義的函數的語法是FindNthField(string,separator,position)

所以位置3將返回three

中使用的分離器實際上是Chr(13)

這必須在Android上運行,所以應該是有效的。

任何建議將不勝感激。

+1

「使用正則表達式,盧克」 – Macarse 2010-11-16 13:13:10

+0

非常感謝 - 這三個例子都是第一次工作。 – Malkoma 2010-11-16 18:35:02

+0

我發現了一個對現在被棄用的Java函數的引用 - peekNthDelimitedField(java.lang.String string,char separator,int nnth,boolean trim) 將給定的字符串視爲分隔符分隔的字符串,並從此字符串返回第n個字段。 – Malkoma 2010-11-16 18:51:55

回答

0

String#split是你的朋友:

private String findNthField(String input, int position) { 
    return findNthField(input, "\n", position); 
} 

private String findNthField(String input, String regExp, int lineNr) { 
    if (input == null || regExp == null || regExp.equals("")) 
    throw new IllegalArgumentException("your message"); 

    String[] parts = input.split(regExp); 
    if (parts.length < lineNr) 
     return "";     // local convention 

    return parts[lineNr-1]; 
} 
+0

非常快速的迴應,它幫助我理解字符串拆分。 – Malkoma 2010-11-16 18:45:00

2

像這樣的事情吧?

public String FindNthField(String string, String separator, int position) { 
    String[] splits = string.split(separator); 
    if (splits.length < position) { 
     return null; 
    } 

    return splits[position - 1]; 
} 

顯然,你separator必須是regex字符串,我沒有做null支票(S)。

+0

@Andreas_D,我實際上覆制了OP的方法......但是如果你願意,我可以很容易地重命名它。 – 2010-11-16 13:19:11

+0

(@Gentlemen - 是的,對不起,先評論,然後看到名稱被複制,然後刪除我的評論;) - 所有在一分鐘內) – 2010-11-16 13:32:11

+0

@Andreas_D,沒有汗...現在,我以前的評論看起來很奇怪,因爲它似乎我回復鬼評論... :) – 2010-11-16 13:34:31

0
import org.junit.Assert; 
import org.junit.Test; 

import java.util.ArrayList; 
import java.util.List; 

public class SplitterTest { 
    @Test 
    public void testFindNthField() { 
     final Splitter splitter = new Splitter(); 
     Assert.assertEquals("result", "three", splitter.findNthField("one*two*three", '*', 3)); 
    } 

    private class Splitter { 
     public String findNthField(final String input, final char separator, final int position) { 
      final List<String> parts = new ArrayList<String>(); 
      final char[] chars = new char[input.length()]; 
      input.getChars(0, input.length(), chars, 0); 
      int wordStart = 0; 
      for (int idx = 0; idx < chars.length; idx++) { 
       if (chars[idx] == separator) { 
        parts.add((String) input.subSequence(wordStart, idx)); 
        wordStart = idx + 1; 
       } 
      } 
      parts.add(input.substring(wordStart)); 
      return parts.get(position - 1); 
     } 
    } 
} 
+0

我發佈了一個基於String.split()的答案,但看到OP想要使用字符分割器,所以我改變了它。 – 2010-11-16 13:44:16

+0

我已經對此進行了計時,並將其與其他兩個字符串分隔符示例進行了比較,它的工作速度是兩倍,儘管它們可以處理字符串分隔符。我會同時使用這兩個版本 - 謝謝 – Malkoma 2010-11-16 18:41:59

+0

@Malkoma:有沒有機會接受這個或另一個呢?如果你正在使用它,也許upvote? – 2010-11-17 13:08:37

相關問題