I have one string and it has limited length of 140 characters. Usually, I get more than 140 in my code. String is set of values in this format: Mxxxx where x can be any number, and it does not have strict length. So I can have M1 or I can have M281 as well.
If string is longer than 140 characters I want to take first 140, but if last one is broken on half, I don't want to have it in my string at all.
Still, I need to save second half in some local variable.
For example, lets say this is the string
"M5903, M6169, M6753, M619, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M669, M6753, M6919, M69, M6753, M6919, M6169, M63, M6919, M6169, M6753, M6919, M619, M653, M6919, M66, M6753, M19, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M619"
And lets say that this are first 140 characters:
"M5903, M6169, M6753, M619, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M6169, M6753, M6919, M6169, M6753, M919, M6169, M6753, M6919, M669, M6753, M6919, M69, M6753, M6919, M6169, M63, M69"
The last value was M6919 but it was splitted to M69 and 19.
What is the most efficient way to say: Split if it's longer than 140, but if last value in new string was spitted on two remove it from first part of string and put it in other string value with the rest of the original string.
There is probably many ways to accomplish this. I could use if or switch/case loops and say if first letter of second string is not 'M', than I know that value was split and I should remove it from the first string, but does someone has cleaner solution than that?
private static string CreateSettlmentStringsForUnstructuredField(string settlementsString)
{
string returnSettlementsString = settlementsString.Replace(", ", " ");
if (returnSettlementsString.Length > 140)
{
returnSettlementsString.Substring(0, 140);
/*if returnSettlementsString was spitted in two in a way
that last value was broken in two parts, take that value
out of returnSettlementStrings and put it in some new
string value with the other half of the string.*/
}
return returnSettlementsString;
}
Something like this may work:
string result;
if (input.Length > 140)
{
result = new string(input.Take(140).ToArray());
if (input[140] != ',') // will ensure that we don´t omit the last complete word if the 140eth character is a comma
result = result.Substring(0, result.LastIndexOf(','));
}
else result = input;
It simply takes the first 140 characters if the total length is greater. Then it searches for the last index of a comma and takes all characters until this comma.
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