修剪 UTF8 缓冲区

Trimming UTF8 buffer

本文关键字:缓冲区 UTF8 修剪      更新时间:2023-10-16

我有一个包含 UTF8 数据的缓冲区。我需要删除前导空格和尾随空格。这是为 ASCII 缓冲区执行此操作(就地)的 C 代码:

char *trim(char *s)
{
  while( isspace(*s) )
    memmove( s, s+1, strlen(s) );
  while( *s && isspace(s[strlen(s)-1]) )
    s[strlen(s)-1] = 0;
  return s;
}

如何对 C/C++ 中的 UTF8 缓冲区执行相同的操作?
附言感谢您提供有关 strlen() 的性能提示。回到 UTF8 特定:如果我需要一起删除所有空格,而不仅仅是在开头和结尾处怎么办?此外,我可能需要删除所有带有 ASCII 代码 <32 的字符。这里有什么针对 UTF8 情况的具体内容,例如使用 mbstowcs()?

你是否也想删除所有不同的Unicode空格,还是只删除ASCII空格?在后一种情况下,您根本不需要修改代码。

无论如何,您使用的反复调用strlen的方法效率极低。它将一个简单的O(n)操作变成至少O(n^2) .

编辑:以下是针对更新问题的一些代码,假设您只想去除 ASCII 空格和控制字符:

unsigned char *in, *out;
for (out = in; *in; in++) if (*in > 32) *out++ = *in;
*out = 0;

>strlen() 扫描到字符串的末尾,因此多次调用它(就像在代码中一样)效率非常低。

尝试查找第一个非空格和最后一个非空格,然后移动子字符串:

char *trim(char *s)
{
  char *first;
  char *last;
  first = s;
  while(isspace(*first))
    ++first;
  last = first + strlen(first) - 1;
  while(last > first && isspace(*last))
    --last;
  memmove(s, first, last - first + 1);
  s[last - first + 1] = '';
  return s;
}

另请记住,代码会修改其参数。