Reputation: 75
I have a variable called Input
Input : STRING (1 .. 80) ;
I use Ada.Strings and Ada.Text_IO as library and I need to know if I can, and how, to remove spaces and special characters (such as the apex, the comma and period) on Input Variable.
Upvotes: 2
Views: 4743
Reputation:
If you have Ada.Strings
, you most likely have Ada.Strings.Fixed
and Ada.Strings.Maps
.
Use the Ada.Strings.Fixed.Translate
method(s) with assistance from Ada.Strings.Maps
to translate any characters to any other characters.
Alternatively you can just loop over your input string and only append characters that you want to a new string. (less elegant, but you dont need any other libraries)
Upvotes: 3
Reputation: 44804
Well, first off you have to understand that if you want to remove a character potentially from the middle of a string, all the characters after the removed character will have to be shifted over to the left one character. This isn't an Ada-specfic issue. If the string is big, this could be rather inefficient. I wouldn't call 80 characters or less "big" though.
The second thing you have to understand is that in Ada, unlike many languages, strings are meant to be perfectly-sized. That means that if you are going to use a String
variable as a buffer (eg: for input via Text_IO), you are going to have to also keep track of the actual length of valid data in it with another variable.
Given that, it can be a simple matter of writing code to recognize the characters you don't want in there, and remove them with something like:
if (Bad_Index < Input_Length) then
Input(Bad_Index .. Input_Length - 1) := Input(Bad_Index + 1 .. Input_Length);
end if;
Input_Length := Input_Length - 1;
However, this is kind of the hard way. If you really have a string you want to manipulate this way, it is probably easiest to put it in an unbounded string object. Ada.Strings.Unbounded.Find_Token
and Ada.Strings.Unbounded.Delete
will do what you need, and all you have to write is a loop around them.
Upvotes: 1
Reputation: 8522
The Ada.Strings.Maps packages would likely be very helpful here, particularly the "To_Set" (define the characters you want to strip out in a Character_Sequence) and "Is_In" functions.
Since you're deleting, rather than replacing, characters, you'll have to iterate through the string, checking to see whether each one "is in" the set of those to be deleted. If so, don't append it to the output string buffer.
Upvotes: 2