Dlang 语言:stripRight 函数去除字符串尾部 'name' 的正确方法
Dlang 语言中,如果使用原样字符串,字符串中的空格和换行符会被保留。因此,使用 stripRight 函数去除字符串尾部的 'name' 时,可能会出现问题。例如以下代码:
import std.stdio;
import std.string;
void main()
{
string testName = q'EOF
test name
EOF';
writeln(testName.stripRight('name'));//怎么还是test name
}
这段代码中,由于使用原样字符串定义了 testName,所以字符串中的空格和换行符都被保留下来了,导致 stripRight 函数无法正常工作。
要解决这个问题,可以使用普通字符串来定义 testName,如下所示:
import std.stdio;
import std.string;
void main()
{
string testName = 'test name\n';
writeln(testName.stripRight('name'));//输出test
}
这里使用普通字符串定义了 testName,然后调用 stripRight 函数去除尾部的 'name',最后输出的结果是 'test ',末尾的空格也被去除了。
因此,在使用 Dlang 语言的 stripRight 函数去除字符串尾部字符时,要注意使用普通字符串而不是原样字符串,避免空格和换行符影响结果。
原文地址: https://www.cveoy.top/t/topic/obNc 著作权归作者所有。请勿转载和采集!