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个字符.
String.Substring从第一个参数开始,并具有第二个参数的长度.您已message.Length作为第二个参数传递,但不起作用.
string firstPart = _message.Substring(0,160);
string rest = _message.Substring(160);
Run Code Online (Sandbox Code Playgroud)
ArgumentOutOfRangeException
如果startIndex小于零或大于字符串的长度,则抛出一个.
对于第二行只是使用
string message2 = _message.Substring(160);
Run Code Online (Sandbox Code Playgroud)
如果您的字符串可能少于160个字符,则应检查该字符串.