c# - 获取带有特殊大小写的字符串的前 140 个字符

标签 c# string split

我有一个字符串,它的长度限制为 140 个字符。 通常,我的代码中有 140 多个。 字符串是以下格式的值集:Mxxxx,其中 x 可以是任何数字,并且没有严格的长度限制。所以我可以有 M1,也可以有 M281。

如果字符串超过 140 个字符,我想取前 140 个,但如果最后一个字符被打断一半,我根本不想在我的字符串中包含它。

不过,我需要将后半部分保存在某个局部变量中。

例如,假设这是字符串

"M5903, M6169, M6753, M619, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M669, M6753, M6919, M69, M6753, M6919, M6169, M63, M6919, M6169, M6753, M6919, M619, M653, M6919, M66, M6753, M19, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M619"

假设这是前 140 个字符:

"M5903, M6169, M6753, M619, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M669, M6753, M6919, M69, M6753, M6919, M6169, M63, M69"

最后一个值是 M6919 但它被拆分为 M6919

最有效的说法是什么:如果长度超过 140,则拆分,但如果新字符串中的最后一个值被吐到两个上,则将其从字符串的第一部分中删除,并将其与原始字符串的其余部分一起放入其他字符串值中字符串。

可能有很多方法可以实现这一点。我可以使用 if 或 switch/case 循环并说如果第二个字符串的第一个字母不是“M”,那么我知道该值被拆分并且我应该将其从第一个字符串中删除,但是有人有比这更干净的解决方案吗?

private static string CreateSettlmentStringsForUnstructuredField(string settlementsString)
{
    string returnSettlementsString = settlementsString.Replace(", ", " ");

    if (returnSettlementsString.Length > 140)
    {
        returnSettlementsString.Substring(0, 140);
        /*if returnSettlementsString was spitted in two in a way 
          that last value was broken in two parts, take that value 
          out of returnSettlementStrings and put it in some new 
          string value with the other half of the string.*/
    }
    return returnSettlementsString;
} 

最佳答案

这样的事情可能会起作用:

string result;
if (input.Length > 140)
{
    result = new string(input.Take(140).ToArray());
    if (input[140] != ',') // will ensure that we don´t omit the last complete word if the 140eth character is a comma
        result = result.Substring(0, result.LastIndexOf(','));
} 
else result = input;

如果总长度更长,它只需要前 140 个字符。然后它搜索逗号的最后一个索引并获取所有字符直到这个逗号。

关于c# - 获取带有特殊大小写的字符串的前 140 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38346085/

相关文章:

c# - 为什么短原语有赋值运算符(&=、+=)但没有非赋值运算符(&、+)?

c++ - 从字符串中获取键/值对并存储在映射中

regex - 使用 PCRE 正则表达式从类似 CSV 的字符串中提取值,包括空字段

ruby - 如何将字符串转换为数组?

javascript - 使用正则表达式分割字符串会产生意想不到的结果

c# - C++ 作为 Windows 游戏编程的第一语言?

c# - 真正的模态窗口可能吗?

c# - WebClient UploadFileAsync 正在进行报告中的奇怪行为

C:检查字符串是否是回文

c - c 中要加倍的数字字符串