Possible Duplicate:
How to split string preserving whole words?可能重复:如何拆分字符串保留整个单词?
I have the following string:
我有以下字符串:
string s = "The Electors shall meet in their respective states to vote by ballot for President and Vice-President.";
I want to take the first 60 characters and split them into two separate strings each of 30 characters or less. Each string must start with a whole word (no partial word, nor space). So this is the desired result:
我想取前60个字符并将它们分成两个单独的字符串,每个字符串不超过30个字符。每个字符串必须以整个单词开头(没有部分单词,也没有空格)。所以这是理想的结果:
string s1 = "The Electors shall meet in"; // 26 characters
string s2 = "their respective states to vot"; // 30 characters
Thank you.
2 个解决方案
#1
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
#2
0
Maybe try calculating the midpoint then work in both directions until you find a space. That would then be your splitting point.
也许尝试计算中点然后在两个方向上工作,直到找到空格。那将是你的分裂点。
#1
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
#2
0
Maybe try calculating the midpoint then work in both directions until you find a space. That would then be your splitting point.
也许尝试计算中点然后在两个方向上工作,直到找到空格。那将是你的分裂点。