Christopher Gosse
Christopher Gosse

Reputation: 23

turbo pascal remove second space from string

This seems simple to me, but I can't get my brain around it. I want to take a string, check for spaces, ignore the first space, but remove all subsequent spaces. For example:

MyString := 'Alexander The Great';

Output would be 'Alexander TheGreat'

Much thanks in advance! (Using Turbo Pascal 7.0 for DOS)

Upvotes: 1

Views: 894

Answers (2)

Christopher Gosse
Christopher Gosse

Reputation: 23

Thank you Mauros for your help, although I figured it out this morning before checking back here. This is the answer, for anyone else who might run into this in the future:

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

And the StripAllSpaces Function looked like this:

FUNCTION  StripAllSpaces(s3:STRING):STRING;
BEGIN
WHILE POS(' ',s3)>0 DO Delete(s3,Pos(' ',s3),1);
StripAllSpaces:=s3;
END;{StripAllSpaces}

And The StripLeadingBlanks / StripTrailingBlanks Functions look like this:

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 } 

Upvotes: 1

aldebaran-ms
aldebaran-ms

Reputation: 666

I usually use Java so I don't know if this is the best way to do what you ask but at least it seems to work...

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.

what have I done? I cicle on the characters of the String. If the character that I found isn't a space I add that to the resulting String. If the character is a 'space' and it is the first (it's the first because count=0) I add 1 to count and add the character to the resulting string. Then if the character is a space again I'll have the count=1 that make me continue ignoring this space.

Upvotes: 2

Related Questions