Strings - Part 1
Strings - Part 1: Overview
Strings are Arrays of Characters
- A String is an array of Characters
- Example:
s: String := "Hi Mom!";
begin
put(s(2));
if s(s'last) = '!' then ...
Questions:
- What is s'last?
- What is the type of s(2) and s(s'last)?
- Which put is called?
Modifying Strings
- Since a string is an array,
we can change elements in the string
- Example:
s: String := "Hi Mom!";
begin
s(4) := 'T';
put_line(s);
s(4 .. 6) := "Ron";
put_line(s);
s := "Hi Mary";
put_line(s);
We can modify
- individual elements in the array
- A slice of the array
- The entire array
But, types must match (ie Character vs String)
And, String sizes must match
Uninitialized Strings?
- We can declare a string without initializing it
- It would be given a value later
- Example:
s: String(1 .. 5);
t: String := "Mama!";
begin
put_line(s); -- What do you think this outputs?
s := "today";
s := t;
Reference vs Value Semantics
- Remember that Ada arrays use value semantics
- In contrast to Java reference semantics
- Contrast with
String s;
String t = "Mama!";
S.o.p(s);
s = "today";
s = t;
Strings are of Fixed Length
- Once declared, a string's length can't change
- Example:
s: String := "Hi Mom!";
t: String := "Bye Mom!";
begin
-- None of these compile:
s := "1234567890";
t := s;
s := t;
-- These are okay:
s := t(1..7);
t(2..8) := s;
Strings and Input
-
ada.text_io.get(s: String)
always inputs s'length
characters
- Example:
s: String(1..10);
len: Natural
begin
get(s);
Like character get, string get skips newlines
String get is frequently too rigid.
Frequently, we use get_line
for more flexibility
Get_line
-
ada.text_io.get_line(s: String; length: Natural)
will input a single
line of data into the string s
- Read only
s'length
-1 or fewer characters
- Example:
s: String(1..10);
len: Natural
begin
get_line(s, len);
put_line(s); -- Does this work?
put_line(s(1..s'length)); -- How about this?
put_line(s(1..len)); -- How about this?
put(len); -- What does this give?
get_line returns
- The next input line (up to the string's size) in the string
- The number of characters read in the length
Get_line - A slight complication
- Get_line acts differently when the input lines are as long or longer than the
input string
- When we use get_line we assume that the input lines are a known length that is
less than the input string length
- Later we will see how to get more flexibility
Get_line in a loop
- We commonly use Get_line in an while not eof loop:
s: String(1..10);
len: Natural
begin
while not end_of_file loop
get_line(s, len);
put_line(s(1..len));
end loop;