Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

03 Programming 1 Lecture Strings in C v01

Uploaded by

abrahamsrashawn
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

03 Programming 1 Lecture Strings in C v01

Uploaded by

abrahamsrashawn
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Programming 1

Lecture 3b
An Introduction to String Manipulation in
the C language
1
Facilitators
SCIT’s Phone Number: 876-9271680-8 ext 2164

• Ms. Arleen Penrose-Whittaker – whittakerstudent@gmail.com


• Mr. Courtney McTavish – cmctavish2017@gmail.com
• Mr. Euton Gordon - eutonbinns@gmail.com
• Mr. Kenrayan Whittle – whittlestudents@outlook.com
• Mr. Horrett Scarlett – hscarlett.utech@gmail.com
• Mr. Laurie Leitch – laurie.leitch@gmail.com
• Mr. Oneil Charles – onielhcharles@gmail.com
• Ms. Sophia McNamarah – smcnamarah@utech.edu.jm or
smcnamarah@gmail.com
• Ms. Nyoka English (BTCC) - nyoka.english@btcc.edu.jm
• Ms. Nathasa Higgin -Thomas (MBCC) - mbcclect2004@yahoo.com
• Mr. Nathaniel Manning - utechstudents2021@gmail.com
• Ms. Natalee Nembhard (MTC) -
natalee.nembhard@moneaguecollege.edu.jm
• Mr. Oral Robinson – oralrobinson1@gmail.com 2

• Mr. Tyrone Edwards - taedwards@utech.edu.jm or


taedwards.cs@gmail.com
Lesson Objectives:
• By the end of this lecture, you should be able to:
1. Describe a string
2. Explain the purpose of the null character
3. Declare a string
4. Describe the rules for declaring a string
5. Initialize a string
6. Describe the purpose of some string functions in the
string header file
7. Copy a string from one variable to another
3
Lesson Objectives Cont’d…
• By the end of this lecture, you should be able to:
9. Join two or more strings
10.Compare two strings
11.Find the length of a string
12.Use escape sequences to format output
13.Use format specifiers to format output
First, Do It By Hand!
Upon being handed a
problem, you may first
want to start coding –
don’t!
First solve the problem
by hand.
If you can’t do that,
then you can’t code it.
5
What is a String?
Your computer programs will have to process
text in addition to numbers.

Text consists of characters: letters, numbers,


punctuation, spaces, and so on.

A string is a sequence of characters.

For example: “Programming is fun!”


Strings

• "programming" is an example of a String.

• Each Character Occupies 1 byte of Memory.

• Size of “programming” = 11 bytes

• In C a string is always Terminated with a NULL Character ('\0').


char word[20] = “‘p’ , ‘r’ , ‘o’ , ‘g’ , ‘r’ , ‘a’ , ‘m’ , ‘m’ , ‘I’ , ‘n’ , ‘g’ ,
‘\0’”
7
NULL Character

• NULL Character is also known as string terminating character.

• It is represented by “\0”.

• NULL Character is having ASCII value 0

• NULL terminates a string, but isn’t part of it

• important for strlen() – length doesn’t include the NULL (will explain later)
8
Declaration Of A String

• Since we cannot declare string using String Data Type, instead of


which we use array of type “char” to create String.
• Syntax :
• char String_Variable_Name [ SIZE ] ;
• Examples :
• char city[30];
• char name[20];
• char message[50];
9
Declaration Activity – 3b.1
char city[30];
char name[20];
char message[50];

From the above answer each of the following questions:


1. How many characters can each string hold
2. Which string can hold the largest number of characters
3. True or False, the strings have been initialized

Write your answers on the next slide


Answer – Activity 3b.1
• <<Type your answers here then remove angled braces>>
Rules For Declaring A String
•String / Character Array Variable name should be legal C Identifier.
•String Variable must have Size specified.
•The statement below will cause compile time error.
•char city[];

•Do not use String as data type because String data type is included in later languages such as C+
+ / Java. C does not support String data type
•When you are using string for other purpose than accepting and printing data then you must
include following header file in your code– #include<string.h>
12
Initializing String (Character Array)
• The process of assigning some legal default data to String is called
initialization of string.
• A string can be initialized in different ways. We will explain this with the help
of an example.
• Below is an example to declare a string with name as str and initialize it with
“GeeksforGeeks”.
o char str[] = "GeeksforGeeks";
o char str[50] = "GeeksforGeeks";
o char str[] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
o char str[14] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'}; 13
String Initializing Example – Activity 3b.2

Enter the following in your text editor:


#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
Copy and paste screen shot of output for the above on the next slide
Activity 3b.2

<<place screen shot of output screen here>>


Functions of string.h
Functi Purpose Example Output
on
Strcpy( Makes a copy of a strcpy(s1, Copies “Hi” to ‘s1’
); string “Hi”); variable
Strcat( Appends a string to the strcat(“Work”, Prints
); end of another “Hard”); “WorkHard”
string
Strcmp Compare two strings strcmp(“hi”, Returns -1.
(); alphabetically “bye”);
Strlen( Returns the number strlen(“Hi”); Returns 2.
); of characters in a
string
Strrev( reverses a given strrev(“Hello olleH
); string ”);
Strlwr(); Converts string to strlwr(“HELL hello
lowercase O”);
Strupr(); Converts string to strupr(“hello HELLO
String Copy (strcpy)
• strcpy( ) function copies contents of one string into another string.
• Syntax : strcpy (destination_string , source_string );
• Example:-strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.

• If destination string length is less than source string, entire source string value won’t be copied
into destination string. For example, consider destination string length is 20 and source string
length is 30. Then, only 20 characters from source string will be copied into destination
string and remaining 10 characters won’t be copied and will be truncated .
String Copy - Activity 3b.3
Copy the following code in your C programming IDE
#include <stdio.h>
#include <string.h>
int main()
{
char string1[50] = “I like programming”;
char string2[50];
strcpy(string2, string1); //copies value on the right to variable on the left
printf(“%s”, string2); //outputs: I like programming
return 0;
}
Activity 3b.3

<<place screen shot of output screen here>>


String Concat (strcat)

• strcat( ) function in C language concatenates (appends) portion of one


string at the end of another string.
• Syntax : strcat ( destination_string , source_string);
• Example:-strcat ( str2, str1); – Copies the contents of str1 to the
string variable str2
• As you know, each string in C is ended up with null character (‘\0’).
20
String Concat (strcat) Cont’d…
• In strcat( ) operation, null character of destination string is overwritten by
source string’s first character and null character is added at the end of new
destination string which is created after strcat( ) operation.
String Concatination (strcat) - Activity 3b.4

Copy the following code in your C programming IDE:


#include <stdio.h>
#include <string.h>
int main()
{
char string1[50] = “Happy programming”;
char string2[50] = “ students”; //note the space before the
word students
printf("%s", strcat(string1, string2)); //outputs: Happy
programming students
return 0;
}
Activity 3b.4

<<place screen shot of output screen here>>


String Compare (strcmp)
• strcmp( ) function in C compares two given strings and returns zero if they
are the same.
• If length of string1 < string2, it returns < 0 value that is -1.
• If length of string1 > string2, it returns > 0 value that is 1
• If length of string1 == string2 it returns 0.
• Syntax : strcmp (str1 , str2 );
• Note: strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as
different characters. 24
Activity 5 - String Compare (strcmp)
Copy the following code in your C programming IDE:
#include <stdio.h>
#include <string.h>
int main()
{
char string1[50] = "Python language";
char string2[50] = "C language";
int result;
result = strcmp(string1, string2);
printf("%d", result);
return 0; // outputs: 13
}
Activity 3b.5

<<place screen shot of output screen here>>


String Length (strlen)

• strlen( ) function in C gives the length of the given


• string.
• Syntax : strlen(str);
• strlen( ) function counts the number of characters in a given string and
returns the integer value.
• It stops counting the character when null character is found. Because,
null character indicates the end of the string in C.

27
String Length (strlen) - Activity 3b.6
Copy the following code in your C programming IDE:

#include <stdio.h>
#include <string.h>
int main()
{
char word[50];
int wordLength;
printf("Enter a word without spaces: ");
scanf("%s", word);
wordLength = strlen(word);
printf("The %s has %d characters", word, wordLength);
return 0;
}
Activity 3b.6

<<place screen shot of output screen here>>


Source:

https://www.gangainstitute.com/wp-content/uploads/2020/04/C
P-STRING.ppt
ESCAPE SEQUENCES
Escape Sequences In C
• As the name denotes, the escape sequence denotes the scenario
in which a character undergoes a change from its normal form
and denotes something that is different than its usual meaning.
• Generally, an escape sequence begins with a backslash ‘\’
followed by a character or characters. The c compiler interprets
any character followed by a ‘\’ as an escape sequence. Escape
sequences are used to format the output text and are not
generally displayed on the screen. Each escape sequence has its
own predefined function.

• Source: https://www.educba.com/escape-sequence-in-c/
Escape Sequences in C
• \n (New line) – We use it to shift the cursor control to the
new line
• \t (Horizontal tab) – We use it to shift the cursor to a
couple of spaces to the right in the same line.
• \a (Audible bell) – A beep is generated indicating the
execution of the program to alert the user.
• \r (Carriage Return) – We use it to position the cursor to
the beginning of the current line.
• \\ (Backslash) – We use it to display the backslash
character.
Escape Sequences in C
• \’ (Apostrophe or single quotation mark) – We use it to
display the single-quotation mark.
• \” (Double quotation mark)- We use it to display the
double-quotation mark.
• \0 (Null character) – We use it to represent the
termination of the string.
• \? (Question mark) – We use it to display the question
mark. (?)
• \nnn (Octal number)- We use it to represent an octal
number.
• \xhh (Hexadecimal number) – We use it to represent a
hexadecimal number.
• \v (Vertical tab)
FORMAT SPECIFIERS
Format Specifiers
• In C programming language, values can be type integer,
floating-point, single character, or sequence of characters.
We use format specifiers in C to display values of a
variable of a different type.
• C contains different format specifiers used in printf() and
scanf() functions; in this tutorial, we will go through a few
important and most commonly used format specifiers in
our C programs.
Why Do We Use C Format
Specifiers?
• Format specifiers in C are used to take inputs and print
the output of a type. The symbol we use in every format
specifier is %. Format specifiers tell the compiler about
the type of data that must be given or input and the type
of data that must be printed on the screen.
The Most Commonly Used Format
Specifiers in C
Format Specifiers Type of Output

%d or %i A decimal integer or signed integer

%c Signed character

%f Signed float

%e A floating-point number

%s A string or sequence of character

%lf double
The Most Commonly Used Format
Specifiers in C
Format Specifiers Type of Output

%Lf Long double

%o Octal integer

%u Short unsigned integer

%ld Long decimal integer


Source
https://www.simplilearn.com/tutorials/c-tutorial/format-
specifiers-in-c
First, Do It By Hand!
Upon being handed a
problem, you may first
want to start coding –
don’t!
First solve the problem
by hand.
If you can’t do that,
then you can’t code it.
41
THANK YOU

42

You might also like