使用超出范围的子字符串拆分字符串

Mat*_*cer 2 c# string substring

我有一条消息说长287个字符.我需要在160个字符之后将其拆分为两个,但我的代码仍然不起作用.我已经搜索了很多,并尝试了许多不同的解决方案,但没有任何工作正如我所期望的那样.在我看来,这是一个简单的解决方案,但在实践中它让我做噩梦!

// a check is done to ensure the message is > 160 in length.    
string _message;
_message = "this is my long message which needs to be split in to two string after 160 characters. This is a long message. This is a long message. This is a long message. This is a long message. This is a long message.";

string message1 = _message.Substring(0,160);
string message2 = _message.Substring(161,_message.Length);
Run Code Online (Sandbox Code Playgroud)

以上只是不起作用 - 在第二个子字符串上给我一个异常错误.

有人可以帮忙吗?消息永远不会超过320个字符.

Tim*_*ter 7

String.Substring从第一个参数开始,并具有第二个参数的长度.您已message.Length作为第二个参数传递,但不起作用.

您只需使用一个参数(从头到尾)即可使用重载:

string firstPart = _message.Substring(0,160);
string rest = _message.Substring(160);
Run Code Online (Sandbox Code Playgroud)

ArgumentOutOfRangeException 如果startIndex小于零或大于字符串的长度,则抛出一个.

演示:http://ideone.com/ZN2BlM


pod*_*ska 6

对于第二行只是使用

string message2 = _message.Substring(160);
Run Code Online (Sandbox Code Playgroud)

如果您的字符串可能少于160个字符,则应检查该字符串.

  • 我一开始犯了同样的错误,但我修好了然后我告诉你和其他人 (2认同)