Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string using substring out of range

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.

like image 662
Matt Facer Avatar asked Nov 28 '25 06:11

Matt Facer


2 Answers

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

like image 96
Tim Schmelter Avatar answered Nov 30 '25 18:11

Tim Schmelter


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.

like image 41
podiluska Avatar answered Nov 30 '25 19:11

podiluska