在D语言中,字符串是不可变的。即使调用了 stripRight() 方法,也不会修改原字符串,而是返回一个新的字符串。因此,需要将返回的新字符串赋值给原字符串变量 four,才能得到去除尾部的效果。

示例代码:

import std.stdio;
import std.algorithm;
import std.string;

void main()
{
    string four = q'EOF
one two
EOF';
    four = four.stripRight('two');
    writeln(four);
}

输出结果:

one

去除尾部空格:

如果想去除尾部的空格,可以使用 stripRight() 函数的无参版本,即:

four = four.stripRight();

这样就会去除字符串末尾的所有空格。

D语言字符串去除尾部字符 - stripRight() 使用解析

原文地址: https://www.cveoy.top/t/topic/obMN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录