2015-08-03 83 views
-1

我有一個字符串,我想要將包含多達N個字符的第一個字組合在一起。包含多達n個字符的子字符串控制字

例如:

String s = "This is some text form which I want to get some first words";

比方說,我想的話最多30個字符,結果應該是這樣的:

This is some text form which

對此有任何方法?我不想重新發明輪子。

編輯:我知道子字符串的方法,但它可以打破單詞。我不希望得到這樣的

This is some text form whi

+1

使用'字符串#子(。,。)' – Satya

+1

是的,有一個叫做'子()'請谷歌的方法。 –

+0

子串打破了這個詞,我不想得到像'這是一些文本形式wh'等 –

回答

1

您可以使用正則表達式來實現此目的。像下面的東西應該做的工作:

String input = "This is some text form which I want to get some first words"; 
    Pattern p = Pattern.compile("(\\b.{25}[^\\s]*)"); 
    Matcher m = p.matcher(input); 
    if(m.find()) 
     System.out.println(m.group(1)); 

這產生了:

This is some text form which 

正則表達式的解釋可以here。我使用了25個字符,因爲前25個字符會導致子字符串中斷,所以您可以將其替換爲您想要的任何值。

+0

'[^ \\ S]'可寫成'\\ S'。另外我不確定'+','*'感覺更好IMO。 – Pshemo

+0

@Pshemo:我同意'*'和'+'。我傾向於更喜歡'[^ \ s]',因爲我認爲它使讀起來更容易一些。 – npinti

+0

真,'[^ \ s]'可能是更容易閱讀,但'\ S'更容易編寫:) – Pshemo

1

分割,空間「」你的字符串,然後的foreach子把它添加到一個新的字符串,然後檢查新的子字符串的長度是否超過或不超過極限。

+0

是啊,我知道如何實現,但我認爲這樣的方法已經存在於某個地方,所以我可以重用它 –

+1

據我知道有沒有這樣的庫... – sgpalit

1

,你可以做這樣的正則表達式沒有

String s = "This is some text form which I want to get some first words"; 
// Check if last character is a whitespace 
int index = s.indexOf(' ', 29-1); 
System.out.println(s.substring(0,index)); 

輸出是This is some text form which;

強制性編輯:在那裏沒有長度檢查,所以照顧它。

相關問題