Bifurcate a string, removing the middle of the string instead of end

171 views Asked by At

I want something similar to this question I found lead me to this answer on another question where I tried to convert it from to my attempt to convert it... failed very badly:

private string trimString(string str, int maxCharacters = 16)
{
        int textLength = str.Length;
        return str.Substring(maxCharacters/2, textLength-maxCharacters).Insert(maxCharacters/2,"...");
}

So doing trimString("123456789", 9) outputs 123...789 when I meant to do something like 123...012 or something similar.. I can't quite figure it out and I've tried many different versions mostly resulting in an input that is out of order.

If it's possible I'd like it to be a simple function and not include other libraries or initializing a new object every call as I plan on using this a lot in a quick session. I'd really like it not to cut off words and place the ellipses however this is not required.

2

There are 2 answers

2
Sergey Kalinichenko On BEST ANSWER

The problem is that Substring(maxCharacters/2, textLength-maxCharacters) into which you insert the ... already has the characters that you don't want to see - 456789. There's no way to fix it after that.

What you should do instead is to pick the prefix and the suffix, and join them together, like this:

private static string trimString(string str, int maxCharacters = 16) {
    if (str.Length <= maxCharacters) {
        return str;
    }
    var suffixLength = maxCharacters / 2;
    // When maxCharacters is odd, prefix will be longer by one character
    var prefixLength = maxCharacters - suffixLength;
    return string.Format(
        "{0}...{1}"
    ,   str.Substring(0, prefixLength)
    ,   str.Substring(str.Length-suffixLength, suffixLength)
    );
}

Demo.

1
fubo On

this returns 123...012 for trimString("123456789012", 6) the first and the last 3 characters, seperated with ....

public static string trimString(string str, int max = 16)
{
    if (str.Length <= max)
    {
        return str;
    }   
    return str.Substring(0, max / 2) + "..." + str.Substring(str.Length - max / 2, max / 2);
}