A Brief Note on Strings and Command Line Arguments
A Brief Note on Strings and Command Line Arguments
Strings and Programming Project 1
Ada Strings vs Java Strings
- Although they have the same name, Ada and Java Strings are significantly different
- Java Strings are very flexible:
- They can change length and/or be reassigned to strings of different strings:
String s = "Hi Mom!";
s = "My favorite course is ITEC 320!";
Ada strings do not have the same flexibility:
- They are fixed length arrays of characters
- Their length must be defined when declared
- Their length cannot change
Unbounded_Strings are flexible like Java Strings
- Package Ada.Strings.Unbounded;
Strings And Programming Assignment 1
- This causes a slight complication in checking whether the command line argument is "-v"
- Complication arises if you try to store the argument in a String variable
Storing a command line argument in a variable
- If you want to store a command line argument in a variable, it must be done correctly
- This does not work:
with Ada.Command_Line; use Ada.Command_Line;
...
s: String;
begin
if argument_count > = 1 then
s := Argument(1);
...
if s = "-v" then
Problem: Length not known
Comparing Strings
- Can compare two strings, without knowing their lengths:
If s = "hi" then
Notice that strings are being compared with =
- Compares character by character
Four Ways to check command line arguments
- Compare directly without using a variable (easiest):
- Declare and initialize a String variable in program's declare section
- Declare and initialize a String variable in a declare block
- Use an Unbounded_String from package Ada.Strings.Unbounded
1. Use a variable
- Compare directly without using a variable :
if argument_count >= 1 then
if argument(1) = "-v" then -- No variable needed
This is the easiest
2. Declare and initialize declaration section
- Can we just initialize in declare section:
s: String := Argument(1);
This works, but only if Argument(1) exists
If Argument_Count=0 then Argument(1) crashes
Solution: Initialize with a conditional expression
procedure whatever is
s: String := (if Argument_Count >= 1 then Argument(1) else "");
begin
This initialize s to either Argument(1) or to the empty string (ie "")
3. Declare and initialize s in a declare block
- A declare block allows a variable to be declared within the execution part (ie between begin
and end)
if argument_count > = 1 then
String_Declare_Block: -- Optional name for the block
declare
s: String := Argument(1);
begin
...
end String_Declare_Block;
end if;
4. Use an Unbounded_String
- Use Unbounded_String from package Ada.Strings.Unbounded
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
...
s: Unbounded_String;
May have to do some conversion between Strings and Unbounded_Strings