这对我来说似乎很简单,但我无法理解它。 我想拿一个字符串,检查空格,忽略第一个空格, 但删除所有后续空格。例如:
MyString:='亚历山大大帝';
输出将是'Alexander TheGreat'
提前多多谢谢! (使用Turbo Pascal 7.0 for DOS)
答案 0 :(得分:1)
我通常使用Java,所以我不知道这是否是你提出要求的最佳方式,但至少它似乎有效...
program nospaces(output);
var
MyString : string;
ResultStr: string;
count: integer;
i: integer;
Temp: string;
n: string;
begin
ResultStr:='';
MyString := 'Alexander The Great';
writeln(MyString);
count := 0;
for i := 1 to length(MyString) do
begin
Temp := copy(MyString, i, 1);
if Temp = ' ' then
begin
If count=0 then
begin
count := count + 1;
ResultStr := ResultStr + Temp;
end;
end
else
begin
ResultStr := ResultStr + Temp;
end
end;
writeln(ResultStr);
readln(n);
end.
我做了什么?我对字符串的字符进行了说明。如果我找到的字符不是空格,我将其添加到结果字符串中。如果角色是一个空间'它是第一个(它是第一个因为count = 0)我将1加1来计算并将字符添加到结果字符串中。然后如果角色又是一个空格,我会让count = 1让我继续忽略这个空间。
答案 1 :(得分:1)
感谢Mauros的帮助,尽管我今天早上在确认之前已经知道了。对于将来可能遇到此问题的其他人来说,这就是答案:
Crush the Name if it has more than one space in it
For example: "Alexander The Great" Becomes "Alexander TheGreat",
"John" stays as "John", "Doc Holiday" stays as "Doc Holiday"
"Alexander The Super Great" becomes "Alexander TheSuperGreat" and
so on and so forth.
FirstSpacePosition := POS(' ',LT.Name);
s := Copy(LT.Name,1,FirstSpacePosition);
s2 := Copy(LT.Name,FirstSpacePosition,Length(LT.Name));
s := StripAllSpaces(s);
s2 := StripAllSpaces(s2);
Insert(' ',s,(Length(s)+1));
LT.Name := s+s2;
StripTrailingBlanks2(LT.Name);
StripLeadingBlanks(LT.Name);
StripAllSpaces功能看起来像这样:
FUNCTION StripAllSpaces(s3:STRING):STRING;
BEGIN
WHILE POS(' ',s3)>0 DO Delete(s3,Pos(' ',s3),1);
StripAllSpaces:=s3;
END;{StripAllSpaces}
StripLeadingBlanks / StripTrailingBlanks函数如下所示:
PROCEDURE StripTrailingBlanks2(var Strg: string);
BEGIN
while Strg[Length(Strg)] = ' ' do
Delete(Strg, Length(Strg), 1);
END; { END StripTrailingBlanks }
PROCEDURE StripLeadingBlanks(var Strg: string);
BEGIN
While (Length(Strg) > 0) and (Strg[1] = ' ') do
Delete(Strg, 1, 1);
END; { END StripLeadingBlanks }