0% found this document useful (0 votes)
9 views

C Programming - Chapter 4 - String

The document discusses strings in C programming. It describes how to declare, initialize and access string elements in C. It also explains various functions to input, output and manipulate strings like strcpy(), strcat(), strlen() etc. and provides examples of using scanf(), printf(), gets() and fgets() functions to read and write strings.

Uploaded by

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

C Programming - Chapter 4 - String

The document discusses strings in C programming. It describes how to declare, initialize and access string elements in C. It also explains various functions to input, output and manipulate strings like strcpy(), strcat(), strlen() etc. and provides examples of using scanf(), printf(), gets() and fgets() functions to read and write strings.

Uploaded by

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

COMPUTER

PROGRAMMING 2
C/C++ LANGUAGE

M.E. LE THANH TUNG


Chapter 4: String
WEEK 4

M.E. LE THANH TUNG


INTRODUCTION
• In C, a string is represented as an array of characters terminated by a null character '\0'.
• The difference between a character array and a C string is the string is terminated with a unique
character ‘\0’. To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters
4 . 1 S T R I N G D E C L A R AT I O N i n C
• String Declaration:
o Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic syntax for
declaring a string.
o Syntax of string declaration:

char string_name [size];

■ char: the data type


■ string_name: name of the string.
■ size: the number of character in string
4 . 2 S T R I N G I N I T I A L I Z AT I O N
• String Initialization : A string in C can be initialized in different ways:
o 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 mystr[] = “Hello“ ;
o 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.
 char mystr[50] = “Hello”;
o Assigning character by character: 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 mystr[50] = {’H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
4 . 2 S T R I N G I N I T I A L I Z AT I O N
• String Initialization:
• Note:
o 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.
o 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 array is only
possible in declaration.
o Since strings are actually arrays in C, you can access a string by referring to its index number inside
square brackets []. The element in the string is distinguished through position, with the first element
has index 0, the second has index 1 and so on.
4.3 STRING ELEMENTS
String Elements:
• Since strings are actually arrays in C, you can access a string by referring to its index number inside
square brackets [].
■ char myStr[50] = “Hello“ ;
■ myStr[0] = ‘h‘;
• The element in the string is distinguished through position, with the first element has index 0, the second
has index 1 and so on.
• Please notice that the element of string is a character, so we must use the single quote (‘ ‘) when
assigning new value for this element.
4.4 STRING INPUT & OUTPUT
4.4.1 Read a String Input From the User:
• Using scanf() function:
o You can use the scanf() function to read a string.
o The scanf() function reads the sequence of characters until it encounters whitespace (space, newline,
tab, etc.).
• char str[];
• scanf( “%s”, str);
• Notice Also notice that we have used the code str instead of &str with scanf(). This is because str is a char
array. Thus, the str in scanf() already points to the address of the first element in the string, which is why we
don't need to use &.
4.4 STRING INPUT & OUTPUT
4.4.1 Read a String Input From the User:
• Read a String Separated by Whitespaces in C:
• Can use multiple methods to read a string separated by spaces in C. The two of the common ones
are:
■ fgets() function to read a line of string
■ gets() to read characters from the standard input (stdin) and store them as a C string until a
newline character.
■ use scanset characters inside the scanf() function
4.4 STRING INPUT & OUTPUT
4.4.1 Read a String Input From the User:
• gets() function:
• gets() is a pre-defined function in C which is used to read a string or a text line. And store the input
in a well-defined string variable.
• The function terminates its reading session as soon as it encounters a newline character.
• char str[];
• gets(str);
• Notice: The gets() function doesn’t have the provision for the case if the input is larger than the buffer.
As a result, memory clogging may occur.
4.4 STRING INPUT & OUTPUT
4.4.1 Read a String Input From the User:
• fgets() function:
• The fgets() function reads a text line or a string from the specified file or console. And then stores it
to the respective string variable.
• Similar to the gets() function, fgets() also terminates reading whenever it encounters a newline
character. But furthermore, unlike gets(), the function also stops when EOF is reached or even if the
string length exceeds the specified limit, n-1.
• char str[];
• fgets(str, n, stream);
• str - It is the variable in which the string is going to be stored
• n - It is the maximum length of the string that should be read
• stream - It is the filehandle, from where the string is to be read.
4.4 STRING INPUT & OUTPUT
4.4.1 Read a String Input From the User:
• scanf() function with scanset character:
• scanf() functions support scanset specifiers which are represented by %[].
• Inside scanset, we can specify single character or range of characters. While processing scanset,
scanf() will process only those characters which are part of scanset.
• We can define scanset by putting characters inside square brackets. Please note that the scansets
are case-sensitive.
• We can also use scanset by providing comma in between the character you want to add
• If first character of scanset is ‘^’, then the specifier will stop reading after first occurrence of that
character.
4.4 STRING INPUT & OUTPUT
4.4.1 Read a String Input From the User:
• scanf() function with scanset character:
• given below scanset will read all characters but stops after first occurrence of ‘\n’ :
• char str[];
• scanf(“%[^\n]s“ ,str);
• given below scanset will read all characters from A-Z and all digits from 0-9:
• char str[];
• scanf(“%[A-Z,0-1]s“ ,str);
4.4 STRING INPUT & OUTPUT
4.4.2 String output:
• Print out string in C:
• Can use multiple methods to output string:
■ printf() function.
■ puts() function.
■ fputs() function
4.4 STRING INPUT & OUTPUT
4.4.2 String output:
• printf() function:
• If we want to do a string output in C stored in memory and we want to output it as it is, then we can
use the printf() function. This function, like scanf() uses the access specifier %s to output strings.
• char str[] = “Hello“;
• printf( “My string: %s”, str);
• Notice any other string that we print after the execution of the printf() line will be printed in the the
same line.
4.4 STRING INPUT & OUTPUT
4.4.2 String output:
• puts() function:
• Another function which we can use to output a string in C is the puts() function.
• The thing to note however is that after printing the given string in the output, the puts() function
transfers the control to the next line. So any other string that we print after the execution of the
puts() line will be printed in the next line by default and not in the same line.
• char str[] = “Hello“;
• puts(str);
4.4 STRING INPUT & OUTPUT
4.4.2 String output:
• fputs() function:
• The fputs() function can be used to output two strings in C without space in between as it does not
transfer the control to a new line so that even if another string is printed after it, both of them will
be on the same line.
• char str[] = “Hello“;
• fputs(str, stdout);
■ stdout - It is the filehandle, from where the string is to be output.
4.5 STRING FUNCTION
• string.h C library: The C language comes bundled with “string.h” which contains some useful string-
handling functions. Some of them are as follows
Function Name Description

strlen(string_name) Returns the length of string name.

strcpy(s1, s2) Copies the contents of string s2 to string s1.

strcmp(str1, str2) Compares the first string with the second string. If strings are the same it returns 0.

strcat(s1, s2) Concat s1 string with s2 string and the result is stored in the first string.

strlwr() Converts string to lowercase.

strupr() Converts string to uppercase.

strstr(s1, s2) Find the first occurrence of s2 in s1.


4.5 STRING FUNCTION
• string.h C library: The C language comes bundled with “string.h” which contains some useful string-
handling functions. Some of them are as follows
strchr() Find the first occurrence of the given character in the string.

strrchr() Finds the last occurrence of the given characters in the string.

strstr() Find the given substring in the string.

strcspn() Returns the span of the source string not containing any character of the given string.

strspn() Returns the span of the source string containing only the characters of the given string.

strpbrk() Finds the first occurrence of any of the characters of the given string in the source string.

strtok() Split the given string into tokens based on some character as a delimiter.
4.5 STRING FUNCTION
// string function
#include <stdio.h>
#include <string.h>
int main()
{
char str[50];
printf("Nhap chuoi: ");
fgets(str, 50, stdin);
int n = strlen(str);
strupr(str);
printf("\nUppercase string: %s " ,str);

return 0;
}
4 . 6 PAT T E R N S E A R C H I N G
• Pattern Searching Problem:
• Pattern matching in C− We have to find if a string is present in another string, as an example, the
string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e.
position it is present at) is displayed. They are very useful when performing a search in a database.
• Features of Pattern Searching Algorithm:
■ Pattern searching algorithms should recognize familiar patterns quickly and accurately.
■ Recognize and classify unfamiliar patterns.
■ Identify patterns even when partly hidden.
■ Recognize patterns quickly with ease, and with automaticity.
4 . 6 PAT T E R N S E A R C H I N G
• Naive Pattern Searching algorithm:
• Naive pattern searching is the simplest method among other pattern-searching algorithms.
• It checks for all characters of the main string to the pattern. This algorithm is helpful for
smaller texts. It does not need any pre-processing phases. We can find the substring by checking
once for the string.
4 . 6 PAT T E R N S E A R C H I N G
• Naive Pattern Searching algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• Rabin Karp algorithm:
• Rabin-Karp algorithm is an algorithm used for searching/matching patterns in the text using a hash
function. Unlike Naive string-matching algorithm, it does not travel through every character in
the initial phase rather it filters the characters that do not match and then perform the comparison.
• Rabin-Karp compares a string’s hash values, rather than the strings themselves. For efficiency, the
hash value of the next position in the text is easily computed from the hash value of the current
position.
4 . 6 PAT T E R N S E A R C H I N G
• Rabin Karp algorithm: Working of Rabin-Karp algorithm
• Initially calculate the hash value of the pattern P.
• Start iterating from the start of the string:
■ Calculate the hash value of the current substring having length m.
■ If the hash value of the current substring and the pattern are same, check if the substring is same
as the pattern.
■ If they are same, store the starting index as a valid answer. Otherwise, continue for the next
substrings.
• Return the starting indices as the required answer.
4 . 6 PAT T E R N S E A R C H I N G
• Rabin Karp algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
• KMP algorithm is used to find a “Pattern” in a “Text”.
• This algorithm compares character by character from left to right. But whenever a mismatch
occurs, it uses a preprocessed table called “Prefix Table” to skip characters comparison while
matching. Sometimes prefix table is also known as LPS Table. Here LPS stands for “Longest
proper Prefix which is also Suffix”.
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
4 . 6 PAT T E R N S E A R C H I N G
• KMP algorithm:
Thank you!

M.E. LE THANH TUNG

You might also like