2012-09-26 52 views
1

可能重複:
How to split string preserving whole words?C# - 如何分割字符串

我有以下字符串:

string s = "The Electors shall meet in their respective states to vote by ballot for President and Vice-President."; 

我要採取的第一個60個字符,將它們分成兩個單獨的字符串,每個字符串不超過30個字符每個字符串必須以整個單詞開頭(不包含部分單詞,也不包含空格)。所以這是期望的結果:

string s1 = "The Electors shall meet in"; // 26 characters 
string s2 = "their respective states to vot"; // 30 characters 

謝謝。

+4

這個問題已經在這裏回答了http://stackoverflow.com/questions/4398270/how-to-split-string-preserving-whole-words。 –

回答

0
string s = "The Electors shall meet in their respective states to vote by ballot for President and Vice-President."; 

string sSub = s.Substring(0,60); //first 60 letters 

string sSubSub = sSub.Substring(0,30); //at most 30 per string 

int index = sSubSub.LastIndexOf(' '); //finds the last space 

string firstString = sSub.Substring(0,index); //first string is up until that space of t he 60-letter string 

string secondSTring = sSub.Substring(index + 1, 30); //second string is the first 30 letters of the rest of the 60-letter string 
+0

明白了。謝謝。剛把secondString改成'sSub.Substring(index + 1,30);' – user1481183

+0

@ user1481183哦,是的,哎呀。很好的接收。 –

0

也許嘗試計算中點,然後在兩個方向上工作,直到找到空間。那就是你的分裂點。