2015-08-03 84 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;

强制性编辑:在那里没有长度检查,所以照顾它。

相关问题