0% found this document useful (0 votes)
28 views49 pages

Slot 16 17 18 Strings

This document covers the fundamentals of string handling in C programming, including how to declare, initialize, and manipulate strings. It discusses various string functions from the standard library, such as input/output operations, string comparison, and concatenation, as well as user-defined functions for string manipulation. Additionally, it addresses the concept of arrays of strings and provides exercises for practical application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views49 pages

Slot 16 17 18 Strings

This document covers the fundamentals of string handling in C programming, including how to declare, initialize, and manipulate strings. It discusses various string functions from the standard library, such as input/output operations, string comparison, and concatenation, as well as user-defined functions for string manipulation. Additionally, it addresses the concept of arrays of strings and provides exercises for practical application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Strings

Programming Fundamentals using C

Objectives
After studying this section, you should be able to:

The way is used to store a string of characters in C.

How to declare/initialize a string in C?

How to access a character in a string?

What are operations on strings
• Input/output (stdio.h)
• Some common used functions in the library string.h

How to manage an array of strings?
25/02/2025 2
Programming Fundamentals using C

Contents

Null-String/C-String

Declare/Initialize a string

Data stored in a string

Output a String

Input a string

May Operators Applied to String?

Other String Functions

Array of Strings
25/02/2025 3
Programming Fundamentals using C

1. Null-String/ C-String

A string is a group of characters. It is similar to an array of characters.

A NULL byte (value of 0 - escape sequence ‘\0’) is inserted to the end of a
string. It is called NULL-string or C-string.

A string is similar to an array of characters. The difference between them is at
the end of a string, a NULL byte is inserted to locate the last meaningful
element in a string.

If a string with the length n is needed, declare it with the length n+1.

25/02/2025 4
Programming Fundamentals using C

2. Declare/ Initialize a String



Static strings: stored in data segment or stack segment. Compiler can determine
the location for storing strings.

Example:

25/02/2025 5
Programming Fundamentals using C

Static Strings: Example

25/02/2025 6
Programming Fundamentals using C

2. Declare/ Initialize a String (cont.)



Dynamic strings: Stored in the heap

Syntax:

char *str = (char *)malloc(length * sizeof(char));


or:
char *str = (char *)calloc(length, sizeof(char));


Note: Using malloc(…) and calloc(…) funtions in <stdlib.h>

25/02/2025 7
Programming Fundamentals using C

Dynamic Strings: Example

25/02/2025 8
Programming Fundamentals using C

3. Data Stored in a strings



Each character in a string is stored as it’s ASCII code.

25/02/2025 9
Programming Fundamentals using C

4. Output Strings
Formatted Output:

printf() library functions support the %s conversion specifier for character string
output

printf() displays all of the characters from the address provided up to but
excluding the null terminator byte. For example:

25/02/2025 10
Programming Fundamentals using C

Formatted Output (cont.)


Qualifiers

Qualifiers on the %s specifier add detail control:
• %20s displays a string right-justified in a field of 20
• %-20s displays a string left-justified in a field of 20
• %20.10s displays the first 10 characters of a string right-justified in a field of 20
• %-20.10s displays the first 10 characters of a string left-justified in a field of 20

For Example:

25/02/2025 11
Programming Fundamentals using C

4. Output Strings (cont.)


Unformatted Output:

puts() library function outputs a character string to the standard

Prototype:
int puts(const char *);

Example:

25/02/2025 12
Programming Fundamentals using C

5. Input Strings: Using scanf(…) function



The scanf() library function support conversion specifiers particularly
designed for character string input. These specifiers are:
• %s - whitespace delimited set.
• %[ ] - rule delimited set

The corresponding argument for these specifiers is the address of the string
to be populated from the input stream. For example:

25/02/2025 13
Programming Fundamentals using C

scanf(…): %s conversion specifier

%s conversion specifier:

Reads all characters until the first whitespace character

Stores the characters read in the char array identified by the corresponding
argument

Stores the null terminator in the char array after accepting the last character

Leaves the delimiting whitespace character and any subsequent characters in
the input buffer

25/02/2025 14
Programming Fundamentals using C

scanf(…): %s conversion specifier (cont.)



Example 1:


The scanf() function will stop accepting input after the character ‘y’ and stores:


The characters ' name is Arnold' remain in the input buffer.

25/02/2025 15
Programming Fundamentals using C

scanf(…): %s conversion specifier (cont.)



Example 2:


The scanf() function will stop accepting input after the character ‘n’ and stores:


The characters ' name is Arnold' remain in the input buffer.

25/02/2025 16
Programming Fundamentals using C

scanf(…): %[^\n] conversion specifier

How to accept blanks in a input string?



%[^\n] conversion specifier:
• Reads all characters until the newline ('\n’)

• Stores the characters read in memory locations starting with the address
passed to scanf
• Stores the null byte in the byte following that where scanf stored the last
character
• Leaves the delimiting character (here, '\n') in the input buffer

25/02/2025 17
Programming Fundamentals using C

%[^\n] conversion specifier: Example



Example 1:


Example 2:

25/02/2025 18
Programming Fundamentals using C

Exercise 1: Input Strings



Compile & Run program

Explain the results of two test cases

Replace and Re-run:
scanf(“%s”, S) scanf(“%10[^\n]”, S)

Why?

Test case 1 Test case 2

25/02/2025 19
Programming Fundamentals using C

scanf(…) - cont.

Some character specifiers used in the function scanf(): Set of character are
or not accepted.

Specifier Description

%[abcd] Searches the input field for any of the characters a, b, c, and d
%[^abcd] Searches the input field for any characters except a, b, c, and d
%[0-9] To catch all decimal digits
%[A-Z] Catches all uppercase letters
%[0-9A-Za-z] Catches all decimal digits and all letters
%[A-FT-Z] Catches all uppercase letters from A to F and from T to Z

25/02/2025 20
Programming Fundamentals using C

5. Input Strings: Using gets(…) function



gets is a standard library function (stdio.h) that:
• Accepts an empty string
• Uses the '\n' as the delimiter
• Throws away the delimiter after accepting the string
• Automatically appends the null byte to the end of the set stored.

The prototype for gets is:
char* gets(char [ ]);

Warning: gets is unsafe. Because it does not check the size of the buffer and
can lead to buffer overflows.

25/02/2025 21
Programming Fundamentals using C

gets(…) function: Example

25/02/2025 22
Programming Fundamentals using C

Exercise 2: Input Strings



Using the hints below, write a program that takes in a string of characters and
prints it out.

Hint:

25/02/2025 23
Programming Fundamentals using C

6. May Operators Applied to String?



C operators act on primitive data type only (char, int, float, …)

Can not be applied to static arrays and static strings.


Example:
We need functions for processing
arrays and string

25/02/2025 24
Programming Fundamentals using C

String Functions: string.h


Common Funtions Description
strlen() Get the length of a string
strcpy() Copy source string to destination string
strcmp() Compare two strings
strcat() Concatenate string src to the end of dest
strupr() Convert a string to uppercase
strlwr() Convert a string to lowercase
strstr() Find the address of a substring
strtok() Breaks string str into a series of tokens separated by delim

25/02/2025 25
Programming Fundamentals using C

strlen() function

The strlen() function calculates the length of a given string. It doesn’t count
the null character ‘\0’.

Syntax: int strlen(const char *str);


Example:

Output:

25/02/2025 26
Programming Fundamentals using C

strcpy() function

The strcpy() is a function used to copy one string to another

Syntax: char* strcpy(char* dest, const char* src);

Example:

Output:

25/02/2025 27
Programming Fundamentals using C

strcmp() function

This function lexicographically compares the first n characters from the two
null-terminated strings and returns an integer based on the outcome.

Syntax: int strcmp(const char *str1, const char *str2);


Example:
Output:

25/02/2025 28
Programming Fundamentals using C

strcat() function

The strcat() function is used for string concatenation. It will append a copy of
the source string to the end of the destination string.

Syntax: char* strcat(char* dest, const char* src);


Example: Output:

25/02/2025 29
Programming Fundamentals using C

strupr() function

The strupr() function is used to converts a given string to uppercase.

Syntax: char *strupr(char *str);

Example:
Output:

25/02/2025 30
Programming Fundamentals using C

strlwr() function

The strlwr() function is used to converts a given string to lowercase.

Syntax: char *strlwr(char *str);

Example:
Output:

25/02/2025 31
Programming Fundamentals using C

strstr() function

The strstr() function is used to search the first occurrence of a substring in
another string.

Syntax: char *strstr (const char *s1, const char *s2);

Example:

Output:

25/02/2025 32
Programming Fundamentals using C

strtok() function

The strtok() function is used to split the string into small tokens based on a
set of delimiter characters.

Syntax: char * strtok(char* str, const char *delims);

Example:
Output:

25/02/2025 33
Programming Fundamentals using C

Exercise 3: Using built-in function (string.h)


Write a program that:

Prompts the user to input two strings.

Compares the two strings and displays whether they are equal or which one
is lexicographically greater.

Concatenates the two strings and displays the result.

Calculates and displays the length of the concatenated string.

Searches for a specific character (input by the user) in the concatenated
string and displays its position (or indicates if it’s not found).

25/02/2025 34
Programming Fundamentals using C

7. Some User-Defined String Functions


Purpose Prototype

Trim blanks at the beginning of a string:


char* lTrim(char s[])
“ Hello” “Hello”

Trim blanks at the end of a string:


char* rTrim(char s[])
“Hello ” “Hello”

Trim extra blanks ins a string:


char* trim (char s[])
“ I am student ” “I am a student”

Convert a string to a name:


char* nameStr( char s[])
“ hoang thi hoa ” “Hoang Thi Hoa”

25/02/2025 35
Programming Fundamentals using C

lTrim() user-defined string function

25/02/2025 36
Programming Fundamentals using C

rTrim() user-defined string function

25/02/2025 37
Programming Fundamentals using C

trim() user-defined string function

25/02/2025 38
Programming Fundamentals using C

nameStr() user-defined string function

25/02/2025 39
Programming Fundamentals using C

Exercise 4:
Suppose that only the blank character is used to separate words in a sentence.
Implement a function for counting number of words in a sentence.

T n u n a n u n o n g t

i 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9

count 0 1 2 3 4 5 6

Counting words in a Criteria for increasing count:


string - s[i] is not a blank and (i==0 or s[i-1] is a
blank)
Do Yourself

25/02/2025 40
Programming Fundamentals using C

Exercise 5:

Counting integers in a string

1 2 n u a 7 n a 9 d f 1 2 3 4 5 9 P 7
0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1
i 0 1 2 3 4 5 6 7 8 9

count 0 1 2 3 4 5

Criteria for increasing count:


- s[i] is a digit and (i==0 or s[i-1] is not a
Do Yourself digit)

25/02/2025 41
Programming Fundamentals using C

Exercise 6: Do Yourself

25/02/2025 42
Programming Fundamentals using C

8. Array of Strings

A string array declaration takes the form

char identifier [numberOfString][number_byte_per_string];


For example, to declare an array of 5 names, where each name holds up to
30 characters, we write:
char names[5][31];
or:
char names[5][31] = { "Harry", "Jean", "Jessica", "Irene", "Jim" };

25/02/2025 43
Programming Fundamentals using C

Array of Strings (cont.)



Example:
Output:

Initialization

25/02/2025 44
Programming Fundamentals using C

Array of Strings: Parameter in a function



Example: Parameter is a Array of
String

Output:

25/02/2025 45
Programming Fundamentals using C

Exercise 7:

Write a C program that will accept 10 names, print out the list, sort the list
using ascending order, print out the result.

Students complete this exercise based
on the code design prototype below.

Hint:

25/02/2025 46
Programming Fundamentals using C

Exercise 7: Sample output

25/02/2025 47
Programming Fundamentals using C

Summary

String in C is terminated by the NULL character (‘\0’)

A string is similar to an array of characters.

All input functions for string will automatically add the NULL character after
the content of the string.

Using the functions on arrays, strings are implemented to operate on arrays
and strings.

If dynamic arrays or strings (using pointers), the assignment can be used on
these pointers.
25/02/2025 48
Programming Fundamentals using C

Summary

String Input
• scanf; gets

• Do yourself using getchar()


String Functions and Arrays of Strings
• Functions: strlen(), strcpy(), strcmp(), strcat(), strupr(), strlwr(), strstr(), strtok()


Arrays of Strings
• Input and Output

• Passing to Functions

• Sorting an Array of Names


25/02/2025 49

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy