I have a message which is say 287 characters long. I need to split it in two after 160 chars, but my code continues to not work. I've googled so much and tried so many different solutions, but nothing is working as I would expect. In my head, this is a simple solution, yet in practice it's causing me nightmares!
// 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);
The above simply doesn't work though - giving me an exception error on the second substring.
Can anyone help? The message will never be more than 320 characters.
String.Substring does start at the first parameter and has a length of the second parameter. You have passed message.Length as second parameter, that doesn't work.
You can use the overload with just one parameter(from start to end):
string firstPart = _message.Substring(0,160);
string rest = _message.Substring(160);
Throws an ArgumentOutOfRangeException
if the startIndex is less than zero or greater than the length of the string.
demo: http://ideone.com/ZN2BlM
For the second line just use
string message2 = _message.Substring(160);
If your string could be less than 160 characters, you should check for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With