0% found this document useful (0 votes)
9 views6 pages

Understanding String Data Structures

The document provides an overview of strings as data structures used for text handling, explaining concepts such as concatenation, substrings, and fixed versus variable length strings. It also covers string handling in the C programming language, including declaration, initialization, and basic operations. Additionally, it highlights the importance of the null character in C strings and demonstrates string manipulation through examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Understanding String Data Structures

The document provides an overview of strings as data structures used for text handling, explaining concepts such as concatenation, substrings, and fixed versus variable length strings. It also covers string handling in the C programming language, including declaration, initialization, and basic operations. Additionally, it highlights the importance of the null character in C strings and demonstrates string manipulation through examples.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

STRINGS

3.0 Introduction
We now turn our attention to data structures that are used for text handling and related
problems. A finite sequence of characters handled as a unit of data is called a string. For
example, ‘ABC, 3gh’, ‘kossynwakeneEmefoh’ and ‘ the cat sat on the mat are literal strings.
In other languages in which strings are used, they are present in the form of one –
dimensional arrays of characters. In the programming language BASIC all strings identifiers
have the “$” sign as a suffix. When strings are joined together, they are said to be
concatenated. So if A ‘Kossy’ and B = ‘kene’ the assignment. C: = AB concatenates A and B
to form C where C = “kossyKene”
Part of a string is called a substring, e.g. A = “kossy” and B = “kene” are substrings of C =”
kossykene”
We shall however, be concerned primarily with strings as data structures composed of
substrings that can be operated upon individually.

3.1 String handling:


String handling notation:
(a) We number each character position in the string in sequence just like the element in
one- dimensional array.
(b) We refer to each substring by taking its first and last character position separated by a
“:” See fig. 3.1(a-d)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

T H E C A T S A T O N T H E M A T
A: = “THE CAT SAT ON THE MAT”

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

T H E C A T S A T O N T H E M A T
A(6:7) : = “AT”

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
T H E C A T S A T O N T H E H A T
A (20:20): =”H”

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
T H E C A T A T E U P T H E M A T
A(9:14): = “ATE UP”
Fig. 3.1 (a, b, c, d)
3.2 Fixed And Variable Length String:
A string may have fixed length or variable length. Fixed length string has fixed number of character
places available for data storage while variable length string provides the data with just the number
of spaces its needs. The manipulation of fixed length and variable length string is often needed in
programming problems.
Character 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 19 2
position 0 1 2 3 4 5 6 7 8 0
content K O S S Y Z I K O A N N T A M A
Comment 1st string 2nd string 3rd string 4th string
Fig. 3.2a Four fixed length string

The diagram above shows four-fixed-length strings concatenated into a single string called F.
Each string is five characters long.

Characte 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 2

r 0

position

content K O S S Y * Z I K O * A N N * T A M A s

o
r

comment 1ststring 2nd string 3rdstring 4th string


Fig. 3.2b Four fixed length string concatenated

The diagram above shows four variable-length string concatenated into a single string called
V. The same data [as in fig. 3.2a] is used but the end of each string is indicated by “*” Note
the saving in storage space.
Discuss: the possible advantage (s) variable length string (s) will have over fixed length
string (s). Discuss also the operations on the strings.
A String in C programming is a sequence of characters terminated
with a null character ‘\0’. The C String is stored as an array of
characters. The difference between a character array and a C string
is the string is terminated with a unique character ‘\0’.

C String Declaration Syntax


Declaring a string in C is as simple as declaring a one-dimensional
array. Below is the basic syntax for declaring a string.
char string_name[size];
In the above syntax str_name is any name given to the string
variable and size is used to define the length of the string, i.e the
number of characters strings will store.
There is an extra terminating character which is the Null
character (‘\0’) used to indicate the termination of a string
that differs strings from normal character arrays.

C String Initialization
A string in C can be initialized in different ways. We will explain this
with the help of an example. Below are the examples to declare a
string with the name str and initialize it with “GeeksforGeeks”.

Ways to Initialize a String in C

We can initialize a C string in 4 different ways which are as follows:


1. Assigning a string literal without size
String literals can be assigned without size. Here, the name of the
string str acts as a pointer because it is an array.
char str[] = "GeeksforGeeks";
2. Assigning a string literal with a predefined size
String literals can be assigned with a predefined size. But we
should always account for one extra space which will be assigned
to the null character. If we want to store a string of size n then we
should always declare a string with a size equal to or greater than
n+1.
char str[50] = "GeeksforGeeks";
3. Assigning character by character with size
We can also assign a string character by character. But we should
remember to set the end character as ‘\0’ which is a null character.
char str[14] =
{ 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning character by character without size
We can assign character by character without size with the NULL
character at the end. The size of the string is determined by the
compiler automatically.
char str[] =
{ 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Note: When a Sequence of characters enclosed in the double
quotation marks is encountered by the compiler, a null character ‘\
0’ is appended at the end of the string by default.
Below is the memory representation of the string “Geeks”.

Note: After declaration, if we want to assign some other text to the


string, we have to assign it one by one or use built-in strcpy()
function because the direct assignment of string literal to character
arrray is only possible in declration.
Note: The C language does not provide an inbuilt data type for
strings but it has an access specifier “%s” which can be used to
print and read strings directly.

// C program to read string from user


#include<stdio.h>

int main()
{
// declaring string
char str[50];

// reading string
scanf("%s",str);

// print string
printf("%s",str);

return 0;
}

// C program to illustrate strings

#include <stdio.h>
#include <string.h>

int main()
{
// declare and initialize string
char str[] = "funaab";

// print string
printf("%6\n", str);

int length = 0;
length = strlen(str);

// displaying the length of string


printf("Length of string str is %d", length);
return 0;
}

Common questions

Powered by AI

Fixed length strings have a set number of character spaces reserved for data storage, regardless of the actual data size, leading to potential unnecessary usage of storage space. Variable length strings, on the other hand, allocate exactly as much space as needed for storage, which can save storage space as no extra characters are left unused . This efficiency in storage is particularly beneficial in systems with limited resources, as it enables better memory utilization .

Fixed-length strings simplify memory allocation by reserving a constant size, reducing fragmentation but potentially wasting space if the reserved size exceeds the needed capacity. This structure can lead to inefficiencies, particularly in applications with diverse data sizes . Conversely, variable-length strings improve space utilization by allocating memory dynamically to match the string's actual length, which reduces wasted space but introduces complexity in memory management. The overhead of managing dynamic memory can also impact performance, especially in systems with high concurrency or limited resources .

In the C programming language, strings are implemented as arrays of characters terminated by a null character '\0'. This terminator distinguishes strings from standard character arrays . Unlike languages with built-in string data types, C utilizes this null character to signify the end of a string, demanding explicit management by the programmer when declaring and manipulating strings . This approach contrasts with higher-level languages that abstract away physical memory considerations from the developer, usually providing more sophisticated built-in string operations and automatic memory management .

Concatenation refers to the process of joining two or more strings together to form a new, larger string. For example, if A = 'Kossy' and B = 'kene', concatenating these strings produces C = 'KossyKene' . This operation is a fundamental text manipulation task in many programming languages, such as using the '+' operator in Python or the 'strcat()' function in C . These techniques enable the construction of complex data strings necessary for various computational tasks.

The null character '\0' is critical in C programming as it marks the end of a string, allowing the language to determine the string's length and prevent overflow errors . Without the null character, operations such as copying or comparing strings could lead to undefined behaviors, memory corruption, or segmentation faults due to invalid memory access. The presence of '\0' thus facilitates safer string handling by defining clear string boundaries, which are crucial for efficient program execution and debugging .

The `strcat()` function in C aids in the process of string concatenation by appending the contents of one string to another. It simplifies concatenation tasks by handling the null character internally, avoiding errors associated with manual concatenation methods where developers need to manage string lengths and terminators explicitly. This function reduces code complexity and minimizes bugs related to buffer overflows or mismanagement of memory boundaries, streamlining operations compared to manual concatenation .

The '%' specifier, particularly '%s', simplifies input and output operations for strings in C by providing a generic way to read and print character arrays. For instance, using `scanf("%s", str)` captures user input into a string variable, and `printf("%s", str)` displays it . These operations up-end manual character handling, streamlining user interactions and reducing code complexity for I/O tasks involving strings, essential for robust application development .

Strings in C can be initialized by directly assigning a string literal, specifying a size with a literal, or assigning each character individually. For example, `char str[] = "GeeksforGeeks"` automatically sizes the array, while `char str[14] = { 'G', 'e', 'e', 'k', 's'...}` initializes with explicit elements . These initializations impact memory management; static size declarations can lead to inefficiencies if the size isn't optimized, whereas dynamic length management via string literals allows flexible and efficient memory usage .

Substrings are referenced by specifying their first and last character positions within a string using a colon. For instance, from the string "THE CAT SAT ON THE MAT," the substring "AT" can be extracted by referencing like this: A(6:7). This notation facilitates efficient text manipulation by allowing individual string segments to be identified and operated upon directly.

A string is defined as a finite sequence of characters treated as a single data unit. For example, the phrase "THE CAT SAT ON THE MAT" is a literal string . A substring is a portion of a string, such as "CAT" or "SAT," which can be referenced by specifying its starting and ending positions in the main string . This referencing method is essential for data manipulation in programmatic operations, allowing programmers to handle and transform text data efficiently.

You might also like