Reputation: 11
In Ada, can we give a string less characters than initially specified ? For example :
Text : String(1..5);
Text := "ada";
Is this code correct? Or are we obliged to give a 5 characters string?
Thank you.
Upvotes: 1
Views: 512
Reputation: 41
Yes, this is possible with Ada.
You can assign a string of smaller length to a fixed string of given length. There is a procedure 'Move' defined under the 'Ada.Strings.Fixed' package.
With the help of this Move Procedure you can assign a smaller string to a given fixed string, pad the remaining indexes with spaces and Justify the copied string Left, Center or Right.
with Ada.Text_IO; use ADA.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Command_Line;
with Ada.Strings;
with Ada.Strings.Fixed;
with Ada.Strings.Bounded;
with Ada.Strings.Unbounded;
procedure fixed_string_ops is
str_1 : String(1 .. 5);
begin
Ada.Strings.Fixed.Move (Source => "Ada", Target => str_1, Drop => Ada.Strings.Right, Justify => Ada.Strings.Right, Pad => Ada.Strings.Space);
Put_Line(str_1);
Ada.Strings.Fixed.Move (Source => "Ada", Target => str_1, Drop => Ada.Strings.Right, Justify => Ada.Strings.Center, Pad => Ada.Strings.Space);
Put_Line(str_1);
Ada.Strings.Fixed.Move (Source => "Ada", Target => str_1, Drop => Ada.Strings.Right, Justify => Ada.Strings.Left,Pad => Ada.Strings.Space);
Put_Line(str_1);
end fixed_string_ops;
compile the above code with
> gnatmake fixed_string_ops.adb
And then run
> fixed_string_ops.exe
Ada
Ada
Ada
You can see the padding and Justification.
Upvotes: 0
Reputation: 1363
The code is not correct, you must either specify 5 characters, e.g.
declare
Text : String(1..5);
begin
Text := "ada ";
end;
or specify the range
declare
Text : String(1..5) := (others => ' '); -- Init to spaces
begin
Text(1..3) := "ada"; -- Text now contains "ada "
end;
or use one of the available string handling packages.
Upvotes: 1
Reputation: 6611
Using the type String
, you have to - like with other array types in Ada - fill all the positions in the array.
But there are a number of tricks:
String
(array) where you declare it, and you don't have to declare the range explicitly:declare
Text : constant String := "Ada";
begin
...
end;
String
(array) you want to put something in:declare
subtype Five_Characters is String (1 .. 5);
Text : Five_Characters := (others => ' ');
begin
Text (2 .. 4) := "Ada";
...
end;
Use Ada.Strings.Unbounded
:
declare
use Ada.Strings.Unbounded;
Text : Unbounded_String;
begin
Text := To_Unbounded_String ("Ada");
...
end;
Upvotes: 6