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.