Section 8.2 - Types of Strings
Actually, single characters aren't all that useful.
Characters are usually found in sequences, and these sequences
are called ``strings''.
Ada 83 provided a built-in type for strings, called String.
String is still a useful type, but many clamored for types which provided
string-like capability but had different trade-offs between ease-of-use
and performance for different tasks.
Thus, Ada 95 provides a number of different ``string'' types, each
best for a certain purpose. All can be converted to and from the
original type String, so you can easily use the different ``string''
types together in a single program.
Here's the list of ``string'' types provided by Ada:
- String
-
This is the basic Ada String type, and is also
called a ``fixed length string''.
This type (String) is simply an array of Characters.
A String value must be given its length when it's created
and its length will stay fixed.
This isn't as bad as it sounds, since there are simple techniques to
handle changing the length of values stored using Strings.
For example, you can use an approach similar to the C programming language -
use access values (pointers) to Strings, which would allow you to
"free" a String and then create a new String with a potentially different
length.
However, if you change a string's length often, other ``string'' types
(Bounded_String or Unbounded_String) are probably a better choice.
-
Bounded_String
-
Values of this type can vary in length up to a maximum length
(which you supply).
This is useful if you know at compile time what the maximum length
of a string will be.
-
Unbounded_String
-
Values of this type can vary in length up to the largest value of
type `Natural' (usually that's over 2 billion characters).
If you have string variables whose length you want to vary, this is
probably the best type to use.
-
Other Language Strings: C.Strings.chars_ptr, COBOL.Alphanumeric,
and Fortran_Character.
-
Ada 95 includes some types that represent strings from other languages,
namely C, COBOL, and Fortran.
If you're interfacing to components written in these other languages,
these types may be very useful to you.
Whenever you enclose characters inside double quotes, "like this", you
are creating a constant of type String.
Remember that a constant of type Character is inside single quotes,
for example, 'L'.
There's a simple rule of thumb to help remember the difference between
constants of types Character and String:
if you want a constant for a single character, use single quotes.
The same symbols are used the same way in C and C++.
Quiz:
Let's say you want to declare a ``string'' variable whose length will vary,
and you don't really know exactly what its maximum length will be.
What type would you probably use?
- String
- Bounded_String
- Unbounded_String
- C.Strings.chars_ptr
You may also:
David A. Wheeler (dwheeler@dwheeler.com)
The master copy of this file is at
"http://www.adahome.com/Tutorials/Lovelace/s8s2.htm".