dlang语言2022年以后如下代码调用了stripRight字符串four还是为one two请帮我分析原因并改正或者给出去除尾部two的方法import stdstdio;import stdalgorithm;import stdstring;void main string four = qEOFone twoEOF; fourstripRighttwo; writeln
在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 著作权归作者所有。请勿转载和采集!