我有一条消息说长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);
上面的功能虽然不起作用 - 在第二个子字符串上给出了异常错误。
有人可以帮忙吗?邮件永远不会超过320个字符。
答案 0 :(得分:7)
String.Substring
从第一个参数开始,并且具有第二个参数的长度。您已将message.Length
作为第二个参数传递,但不起作用。
您可以使用overload with just one parameter(从开始到结束):
string firstPart = _message.Substring(0,160);
string rest = _message.Substring(160);
引发ArgumentOutOfRangeException
如果startIndex小于零或大于字符串的长度。
答案 1 :(得分:6)
对于第二行,只需使用
string message2 = _message.Substring(160);
如果你的字符串少于160个字符,你应该检查一下。
答案 2 :(得分:4)
string message1 = _message.Substring(0,160);
string message2 = _message.Substring(160,_message.Length - 160);
请参阅This使用两个参数substring。
答案 3 :(得分:1)
String.Substring function有一个重载,它没有取长度参数,只是转到字符串的末尾。您可以通过以下方式简化代码:
string message1 = _message.Substring(0,160);
string message2 = _message.Substring(160);
答案 4 :(得分:1)
Substring方法的第二个参数接收您要从_message获取的数字或字符。而是这样做:
string message1 = _message.Substring(0,160);
string message2 = _message.Substring(160,_message.Length-160);
答案 5 :(得分:0)
根据http://msdn.microsoft.com/en-us/library/aa904308(v=vs.71).aspx,该函数具有以下足迹:substring(int start)或substring(int start,int length)
意味着您调用它的方式是:从位置160开始复制,并继续执行字符串的总长度。 因此,如果您的字符串长度为287个字符,那么您可以使用
告诉它string message2 = _message.Substring(161,_message.Length);
从位置161开始复制,并继续以下287个字符。在这种情况下,字符串必须是161 + 287个字符,这是导致错误的原因。
您应该使用:
string _message;
_message ="这是我的长消息,需要在160个字符后分成两个字符串。这是一条很长的信息。这是一条很长的信息。这是一条很长的信息。这是一条很长的信息。这是一条很长的信息。&#34 ;; string message1 = _message.Substring(0,160);
string message2 = _message.Substring(message1.Length,_message.Length - message1.Length);
这将导致消息的长度为287 - 160 = 127。