修剪 UTF8 缓冲区
Trimming UTF8 buffer
我有一个包含 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;
}
另请记住,代码会修改其参数。
相关文章:
- C++字符*缓冲区的大小
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- ostream过载时的缓冲区冲洗
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- Xaudio2在更改缓冲区或循环时弹出声音
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 多线程双缓冲区
- Android P-9.0.0_r53 Logcat主缓冲区超出定义大小
- 套接字读取后,我在缓冲区中看到意外输入
- std::带有自定义缓冲区的 iostream 不允许我写入
- 从返回的顶点缓冲区查询顶点结构
- Vulkan 中的动态顶点缓冲区格式设置
- OpenGL 16 位模板缓冲区?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 在 openGL 中多次绑定缓冲区
- 修剪 UTF8 缓冲区
- c++使用宽流读取UTF8缓冲区