Concat arabic and english string with string.Forma

2019-07-31 17:23发布

问题:

Have some trouble with concat two string.

return string.Format("{0}{1}{2}",
            IdWithSubType,

            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");

it's ok when IdWithSubType, extrainfo and context has latin or kirillic symbols, but IdWithSubType can be arabic, and concat with that is wrong. e.g.100252575)طائرات هليكوبت@vk.com) arabic and other symbols mixed, but i need something like "here arabic string" (100252575@vk.com. it would be great if this problem have solve with String.Format. Hope for your help. Thank you

回答1:

It's likely no encoding issues appear there, just how RTL (right-to-left) string follows arrangement as part of LTR (left-to-right) string.

There's 2 characters which commonly used in bidirectional formatting to mark either LTR & RTL part, assigned as 0x200e (LTR) & 0x200f (RTL). In this case, use 0x200e to mark end of RTL part (in Arabic) and starting LTR part:

string leftToRight = ((char)0x200E).ToString();

// using string.Format
return string.Format("{0}{1}{2}{3}",
            IdWithSubType,
            leftToRight,

            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");,

// alternative: using string.Join
return string.Join(leftToRight, IdWithSubType,
            ExtraInfo.Any(info => info.InfoType == UniExtraInfoType.Alias)
            ? string.Format(" ({0})", string.Join(",", ExtraInfo.First(info => info.InfoType == UniExtraInfoType.Alias).Info))
            : "",

            Context != null
            ? string.Format(" ({0})", Context.IdWithSubType)
            : "");,

Demo: .NET Fiddle Example

Similar issues:

incorrect right to left concatenation english and Arabic

Problem creating correct path concatenating left to right with right to left sections