0% found this document useful (0 votes)
7 views14 pages

PF LEC7

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)
7 views14 pages

PF LEC7

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/ 14

PROGRAMMING LECTURE 7

FUNDAMENTALS
STRINGS
Strings are used for storing text/characters.
For example, "Hello World" is a string of characters.

To output the string, you can use the printf() function together with
the format specifier %s to tell C that we are now working with
strings:
ACCESS STRINGS

you can access a string by referring to its index number inside


square brackets [].
This example prints the first character (0) in greetings:
MODIFY STRINGS

To change the value of a specific character in a string, refer to the


index number, and use single quotes:
LOOP THROUGH A STRING

You can also loop through the characters of a string, using a for
loop:
ANOTHER WAY OF CREATING STRINGS

In the examples above, we used a "string literal" to create a string


variable. This is the easiest way to create a string in C.
You should also note that you can create a string with a set of
characters. This example will produce the same result as the
example in the beginning of this page:
STRINGS - SPECIAL CHARACTERS

Because strings must be written within quotes, C will


misunderstand this string, and generate an error:

The solution to avoid this problem, is to use the backslash escape


character.
The backslash (\) escape character turns special characters into
string characters:
The sequence \" inserts a double quote in a string:

The sequence \' inserts a single quote in a string:


CONT….
The sequence \\ inserts a single backslash in a string:
STRING FUNCTIONS

C also has many useful string functions, which can be used to


perform certain operations on strings.
To use them, you must include the <string.h> header file in your
program:

String Length
For example, to get the length of a string, you can use the
strlen() function:
EXAMPLE OF STRLEN

It is also important that you know that sizeof will always return the memory size (in bytes), and not the actual string length:
CONCATENATE STRINGS

To concatenate (combine) two strings, you can use the strcat()


function:
COPY STRINGS

To copy the value of one string to another, you can use the strcpy()
function:
COMPARE STRINGS

To compare two strings, you can use the strcmp() function.

It returns 0 if the two strings are equal, otherwise a value that is


not 0:

You might also like