在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();

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


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

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