0

Does anyone know of an implementation of the php function mb_strcut in C#?

http://php.net/manual/en/function.mb-strcut.php

mb_strcut() extracts a substring from a string similarly to mb_substr(), but operates on bytes instead of characters. If the cut position happens to be between two bytes of a multi-byte character, the cut is performed starting from the first byte of that character. This is also the difference to the substr() function, which would simply cut the string between the bytes and thus result in a malformed byte sequence.

Madu Alikor
  • 2,544
  • 4
  • 21
  • 36
  • 2
    Give specific examples of what you want to get in the end. Show examples on how exactly you expect `mb_strcut` to differ from `substring` – Ilya Ivanov Feb 12 '13 at 09:15
  • Please describe what you're trying to do; don't state your requirements in terms of functionality of another programming language. – dtb Feb 12 '13 at 09:16
  • 1
    Possible solution here? http://stackoverflow.com/questions/1225052/best-way-to-shorten-utf8-string-based-on-byte-length – dash Feb 12 '13 at 09:21

1 Answers1

0

Thanks Dash could have not written the below without your help

    public static string LimitByteLength(string input, int startByte, int byteLength)
    {
        var maxLength = startByte + byteLength;
        return 
            new string(
                input.SkipWhile((c, i) => GetByteCount(input.Substring(0, i + 1)) <= startByte)
                    .TakeWhile((c, i) => GetByteCount(input.Substring(0, i + 1)) <= maxLength).ToArray());
    }

    private static int GetByteCount(string input)
    {
        return Encoding.Unicode.GetByteCount(input);
    }
Madu Alikor
  • 2,544
  • 4
  • 21
  • 36