Ada: Strings

Ada: Strings

Learn string handling with Ada

Ada strings are a fundamental data type in Ada programming language. They are used to represent sequences of characters and are essential for handling text data. Ada provides two main types of strings: fixed-length strings and unbounded-length strings.

Fixed-Length Strings

Fixed-length strings are arrays of characters with a predefined length. This means that the size of the string is known at compile time and cannot be changed during program execution. Fixed-length strings are declared using the string type specifier, followed by a range of indices indicating the beginning and ending positions of the characters. For instance, the following declaration defines a string variable my_name with a length of 10 characters:

Declaration:

 my_name : string(1..10);

Fixed-length strings are primarily used for efficient processing of fixed-size text data. They are often used in situations where the size of the text is known in advance or where the string is used as a key or index in a data structure.

Unbounded-Length Strings

Unbounded-length strings, also known as dynamic strings, do not have a predefined length. Instead, their length is determined during program execution. Unbounded-length strings are declared using the unbounded_string type specifier. Unlike fixed-length strings, unbounded-length strings require additional operations for managing memory allocation and deallocation.

Ada declaration

my_message: unbounded_string ;

Unbounded-length strings are useful for handling variable-length text data, such as text input from the user or data fetched from files. They provide more flexibility and flexibility than fixed-length strings, but they also require more careful memory management.

Working with Strings in Ada

Ada provides a rich set of operations for manipulating strings, including:

  • Accessing individual characters: Strings are indexed using subscript notation, similar to arrays. For instance, to access the first character of the string my_name, you can use my_name(1).

  • String concatenation: The & operator is used to concatenate two strings, creating a new string with the characters of both strings. For example, the statement result := "Hello" & "World" will assign the string "HelloWorld" to the variable result.

  • String comparison: The =", !=, <, >, <=, and >= operators can be used to compare strings for equality, inequality, ordering, and so on.

  • String manipulation: Ada provides various functions for manipulating strings, such as converting upper case to lowercase, trimming leading and trailing whitespace, and extracting substrings.

Examples of String Manipulation

Here are some examples of string manipulation in Ada:

Ada

-- Concatenating strings
message: string  := "Hello";
message := message & " " & "World!";
Put_Line(message);

-- Comparing strings
name: string := "John";
greeting: string  := "Hello " & name;
if greeting = "Hello John" then
  Put_Line("Greetings are correct");
else
  Put_Line("Greetings mismatch");
end if;

-- Extracting substrings
sentence: string  := "Today is a beautiful day";
today: string := sentence(1..5);
nice: string := sentence(11..15);
Put_Line(today & " is a " & nice);

These examples demonstrate the basic operations for handling strings in Ada. More complex string manipulations can be achieved using the various functions and packages provided by the Ada standard library.


Calling a method

In Ada, the apostrophe (`) character is used to access methods or properties of objects. This is different from some other programming languages, such as Java or Python, where the dot (.) character is used for this purpose.

The use of the apostrophe to denote method calls is a unique feature of Ada. It is believed that this notation was chosen to distinguish between object access and dot notation, which is used for other purposes in Ada, such as accessing fields of records or components of arrays.

Here is an example of how to use the apostrophe to access a method of a string object:

Code snippet

message: string  := "Hello";
Put_Line(message'Length);

In this example, the message'Length expression accesses the Length method of the message string object. The apostrophe indicates that this is a method call and the Length identifier specifies the name of the method.

The use of the apostrophe for method calls is consistent with Ada's overall syntax and naming conventions. It provides a clear and unambiguous way to distinguish between object access and other uses of dot notation.


Empty parenthesis ()

In Ada, parentheses are not required for subprogram calls when there are no arguments to pass. This is consistent with the language's philosophy of emphasizing conciseness and readability.

The absence of parentheses for argumentless subprogram calls is a deliberate design choice. It helps to reduce visual clutter and make the code more straightforward to understand, especially for simple subprogram invocations. By eliminating the need for parentheses, Ada promotes code that is easier to read and interpret.

This approach is similar to how Ada handles string method calls without parentheses. The language recognizes that certain operations, such as invoking a subprogram without arguments or accessing a string method, are common and repetitive. By omitting parentheses in these cases, Ada reduces the visual noise and makes the code more concise.

While the lack of parentheses for argumentless subprogram calls may seem unconventional compared to other languages, it aligns with Ada's overall principles of clarity and readability. Ada's strong static typing and explicit language constructs aim to minimize ambiguity and prevent runtime errors. The omission of parentheses for argumentless subprogram calls is an extension of this principle, promoting code that is easier to read and maintain.

It's important to note that Ada still allows parentheses for argumentless subprogram calls, and they are sometimes used for emphasis or to avoid potential parsing ambiguities. However, the default and preferred style is to omit parentheses, reflecting the language's emphasis on conciseness and readability.


Methods & Properties

In Ada methods start with uppercase!

Method/PropertyDescription
LengthReturns the length of the string.
ToUpperConverts the string to uppercase.
ToLowerConverts the string to lowercase.
TrimRemoves leading and trailing whitespace from the string.
SubString(StartPos, EndPos)Extracts a substring from the string, starting at StartPos and ending at EndPos.
Index(SubString)Finds the first occurrence of SubString in the string.
PosReturns the position of the string within a larger string.
Equal(OtherString)Checks if the string is equal to OtherString.
NotEqual(OtherString)Checks if the string is not equal to OtherString.
Less(OtherString)Checks if the string is less than OtherString in lexicographical order.
LessEqual(OtherString)Checks if the string is less than or equal to OtherString in lexicographical order.
Greater(OtherString)Checks if the string is greater than OtherString in lexicographical order.
GreaterEqual(OtherString)Checks if the string is greater than or equal to OtherString in lexicographical order.

String Equality

Yes, you can compare two strings using the = operator in Ada. The = operator checks for equality between two operands. In the case of strings, it checks if the two strings have the same sequence of characters.

Code snippet

string message1 := "Hello";
string message2 := "World";
boolean isSame := message1 = message2;
Put_Line(isSame);

This code will print the following output:

False

This is because the two strings message1 and message2 have different sequences of characters.

You can also use the /= operator to check for inequality between two strings. The /= operator checks if the two operands are not equal.

Code snippet

string message1 := "Hello";
string message2 := "World";
boolean isDifferent := message1 /= message2;
Put_Line(isDifferent);

This code will print the following output:

True

This is because the two strings message1 and message2 are not equal.

Note: This is different in Java, operator == can't be used to compare two strings. This can be confusing for some new developers of Java but in Ada things are normal.


Parsing a string

Parsing a string to convert it to numbers in Ada can be done using the Integer'Value or Float'Value function. These functions take a string as input and return the corresponding integer or float value, respectively.

Here's an example of how to use Integer'Value to convert a string to an integer:

Code snippet

with Ada.Text_IO;
procedure Main is
   Input : String (1..20);
   Number : Integer;
begin
   Put ("Enter a number: ");
   Get_Line (Input, Length);
   Number := Integer'Value (Input);
   Put_Line (Number);
end Main;

This code will prompt the user to enter a number, and then it will convert the input string to an integer and print it to the console.

Here's an example of how to use Float'Value to convert a string to a float:

Code snippet

with Ada.Text_IO;
procedure Main is
   Input : String (1..20);
   Number : Float;
begin
   Put ("Enter a number: ");
   Get_Line (Input, Length);
   Number := Float'Value (Input);
   Put_Line (Number);
end Main;

This code will prompt the user to enter a number, and then it will convert the input string to a float and print it to the console.

It is important to note that if the input string does not contain a valid number, then an exception will be raised. You can use a try-catch block to handle this exception, as shown in the following example:

Code snippet

with Ada.Text_IO;
procedure Main is
   Input : String (1..20);
   Number : Integer;
begin
   Put ("Enter a number: ");
   Get_Line (Input, Length);
   try
      Number := Integer'Value (Input);
   except
      When others =>
         Put_Line ("Invalid input.");
   end try;
   Put_Line (Number);
end Main;

This code will prompt the user to enter a number, and then it will try to convert the input string to an integer. If the conversion is successful, then the number will be printed to the console. Otherwise, an exception will be raised and the message "Invalid input." will be printed to the console.


Disclaim: This article is created with Bard, not with Rix.