2015-02-07 78 views
1

這對我來說似乎很簡單,但我無法讓我的大腦圍繞它。 我想要一個字符串,檢查空格,忽略第一個空格, 但刪除所有後續空格。例如:渦輪pascal從字符串中刪除第二個空格

MyString:='Alexander The Great';

輸出將是'亞歷山大大帝'

非常感謝提前! (使用Turbo Pascal的7.0 DOS)

回答

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 } 
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來計數並將字符添加到結果字符串中。然後如果角色再次成爲空間,我會讓count = 1讓我繼續忽略這個空間。