你正在寻找的是null字符值。使用空字符串,它是一个长度为零的实体。但是没有长度不为零的字符。 null您正在查找的字符值根本不存在。
看到这个的另一种方法是考虑什么Length(mystring)
在你的循环结束。无论您使用mystring[k] := ...
分配的字符是什么,mystring
的长度都不会被修改。
所以,你可以做一个新的字符串,而不是修改现有的字符串。例如:
var
new: string;
len: Integer;
....
SetLength(new, Length(mystring));
len := 0;
for i := 1 to Length(mystring) do
begin
if not (mystring[i] in ['a','e','i','o','u']) then
begin
inc(len);
new[len] := mystring[i];
end;
end;
SetLength(new, len);
mystring := new;
或者你可以把重复调用StringReplace
:
mystring := StringReplace(mystring, 'a', '', [rfReplaceAll]);
mystring := StringReplace(mystring, 'e', '', [rfReplaceAll]);
//etc.
这个版本使用StringReplace
比第一种方法更慢。
另一种方法是在地方工作:
var
len: Integer;
....
len := 0;
for i := 1 to Length(mystring) do
begin
if not (mystring[i] in ['a','e','i','o','u']) then
begin
inc(len);
mystring[len] := mystring[i];
end;
end;
SetLength(mystring, len);
空字符串''''不是字符。这是呃空弦。你正在使用哪个版本的Delphi?你可以在你的问题中添加一个Delphi版本标签吗? – TLama
使用#0而不是''作为mystring [k]:=''' – Alexandr
@Alexandr不,不要那样做。想想当你把字符串放进编辑控件时会发生什么。 –