【发布时间】:2014-10-24 02:04:43
【问题描述】:
我在 C 中有一个 char * 字符串,它基于用户输入。从这个字符串中,我想从第一个位置开始选择一个子字符串,这样生成的子字符串在固定宽度的终端上是 n 列宽。
过去从未使用过非 ASCII 字符,我完全不知道如何解决这个问题,甚至开始。一些初步搜索建议使用libiconv,但这似乎没有帮助。我也尝试使用wchar.h,广泛的字符支持,但我不确定这是正确的方法。
编辑:这是我第一次尝试的尝试:
static int
count_n_cols (const char *mbs, char *mbf, const int n)
{
wchar_t wc;
int bytes;
int remaining = strlen(mbs);
int cols = 0;
int wccols;
while (*mbs != '\0' && cols <= n)
{
bytes = mbtowc (&wc, mbs, remaining);
assert (bytes != 0); /* Only happens when *mbs == '\0' */
if (bytes == -1)
{
/* Invalid sequence. We'll just have to fudge it. */
return cols + remaining;
}
mbs += bytes;
remaining -= bytes;
wccols = wcwidth(wc);
*mbf += wc;
cols += (wccols == -1? 1 : wccols);
}
return cols;
}
【问题讨论】:
-
添加了我尝试编写的函数。我不确定这是否是最好的前进方式。
-
您的代码有什么问题?乍一看还不错。