【问题标题】:c# - How to split a string [duplicate]c# - 如何拆分字符串[重复]
【发布时间】:2012-09-18 14:29:20
【问题描述】:

可能重复:
How to split string preserving whole words?

我有以下字符串:

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

谢谢。

【问题讨论】:

标签: c# asp.net vb.net visual-studio


【解决方案1】:

也许尝试计算中点,然后在两个方向上工作,直到找到一个空间。那将是你的分裂点。

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • 知道了。谢谢你。刚刚将 secondString 更改为 sSub.Substring(index+1, 30);
    • @user1481183 哦,是的,哎呀。不错的收获。
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多