0

How to calculate the display width of a string in c# console program (.net core)?

var str = "hello你好こんにちは"; 
var length = str.Length; // 12
var width = Str.Width(str); // expected width: 19
public static int Width(string str)
{
    var length = 0;
    for(var i = 0; i < str.Length; i++)
    {
        byte[] bytes = Encoding.Default.GetBytes(str.Substring(i,1));
        if(bytes.Length > 1)
        {
            length += 2;
        }
        else
        {
            length += 1;
        }
    }
    return length;
}

I can't guarantee that this will get the right results in all languages.

So what should I do to make this function work in all languages? like the mb_strwidth function in PHP.

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
candycat
  • 435
  • 4
  • 13
  • Please be advised that Unicode characters [don't work that well with the Console](https://stackoverflow.com/a/3971750/4934172). – 41686d6564 stands w. Palestine Apr 12 '19 at 03:24
  • Also i am not sure that you could do this anyway, it depends on the font id assume – TheGeneral Apr 12 '19 at 03:25
  • thank @Ahmed Abdelhameed recommend.In many cases we need to get the width of multi-language shuffle, not just for the console. so how can I implement this function better? – candycat Apr 12 '19 at 03:37
  • C# strings are Unicode strings. That's why `char` is a 2 byte in size. Your string is 12 characters length so `"hello你好こんにちは".Length == 12`. Why it should be 19? – vasily.sib Apr 12 '19 at 05:02
  • Oh, I see now. You want to know how many bytes this string will occupy when displayed in a single-byte encoded console? Linq to the resque! `var length = "hello你好こんにちは".Aggregate(0, (r, c) => r += c < 256 ? 1 : 2); // 19` – vasily.sib Apr 12 '19 at 05:24

0 Answers0