Document Details

BonnySheep

Uploaded by BonnySheep

First-Year Engineering Department

Ms. Dhanashree S. Tayade

Tags

C programming strings C programming structures programming fundamentals computer science

Summary

This document provides an explanation and examples of strings and structures in C programming. It's suitable for first-year engineering students.

Full Transcript

UNIT IV Strings and Structure Ms. Dhanashree S. Tayade, M.E. (CSE), PhD pursuing Assistant Professor First Year Engineering Department 1 Outline Strings: What are Strings? String declaration, String initializatio...

UNIT IV Strings and Structure Ms. Dhanashree S. Tayade, M.E. (CSE), PhD pursuing Assistant Professor First Year Engineering Department 1 Outline Strings: What are Strings? String declaration, String initialization, Standard Library String Functions, String operations without string library functions. Structures: Why use Structures? Declaring a Structure, Accessing Structure Elements, How Structure Elements are Stored? Array of Structure. 2 What are Strings? In C programming, a string is a sequence of characters terminated with a null character \0. Example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default. 3 How to declare a string? Here's how you can declare strings: char s; String Declaration in C Here, we have declared a string of 5 characters. 4 How to initialize strings? You can initialize strings in a number of ways. char c[] = "abcd"; char c = "abcd"; String Initialization in C char c[] = {'a', 'b', 'c', 'd', '\0'}; char c = {'a', 'b', 'c', 'd', '\0'}; 5 How to initialize strings? Let's take another example: char c = "abcde"; Here, we are trying to assign 6 characters (the last character is '\0') to a char array having 5 characters. This is bad and you should never do this. 6 Assigning Values to Strings Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example, char c; c = "C programming"; // Error! array type is not assignable. 7 Read String from the user You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.). 8 Example 1: scanf() to read a string #include Output int main() Enter name: Dennis Ritchie { Your name is Dennis. char name; printf("Enter name: "); Even though Dennis Ritchie was scanf("%s", name); entered in the above program, only "Dennis" was stored in the name printf("Your name is %s.", name); string. return 0; It's because there was a space after } Dennis. 9 Example 1: Continued… Also notice that we have used the code name instead of &name with scanf(). scanf("%s", name); This is because name is a char array, and we know that array names decay to pointers in C. Thus, the name in scanf() already points to the address of the first element in the string, which is why we don't need to use &. 10 Standard Library String Functions strlen() - calculates the length of a string strcpy() - copies a string to another strcmp() - compares two strings strcat() - concatenates two strings 11 strlen( ) The strlen() function calculates the length of a given string. The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (an unsigned integer type). It is defined in the header file. 12 Example: strlen() function #include #include Output: int main() Length of string a = 7 { Length of string b = 7 char a="Program"; char b={'P','r','o','g','r','a','m','\0'}; // using the %zu format specifier to print size_t unsigned integral data type printf("Length of string a = %zu \n",strlen(a)); printf("Length of string b = %zu \n",strlen(b)); return 0; } 13 strcpy( ) The function syntax of strcpy() is: char strcpy(char destination, const char source); The strcpy() function copies the string pointed by source (including the null character) to the destination. The strcpy() function also returns the copied string. The strcpy() function is defined in the header file. 14 Example: strcpy( ) function #include Output #include C programming int main() { char str1 = "C programming"; char str2; strcpy(str2, str1); // copying str1 to str2 printf("%s", str2); // C programming return 0; } 15 strcmp( ) The strcmp() compares two strings character by character. If the strings are equal, the function returns 0. The function syntax of strcmp() is: int strcmp (const char str1, const char str2); The strcmp() function is defined in the header file. 16 Example: strcmp( ) function #include #include Output int main() { strcmp(str1, str2) = 1 char str1[] = “abcd”; strcmp(str1, str3) = 0 char str2[] = “abCd”; char str3[] = “abcd”; int result; result = strcmp(str1, str2); // comparing strings str1 and str2 printf("strcmp(str1, str2) = %d\n", result); result = strcmp(str1, str3); // comparing strings str1 and str3 printf("strcmp(str1, str3) = %d\n", result); return 0; } 17 strcat( ) In C programming, the strcat() function concatenates (joins) two strings. The function definition of strcat() is: char *strcat(char *destination, const char *source) The strcat() function concatenates the destination string and the source string, and the result is stored in the destination string. It is defined in the header file. 18 Example: strcat( ) function #include Output #include int main() String 1=This is PPS Lecture String 2= PPS Lecture { char str1 = "This is" ; char str2[] = " PPS Lecture"; // the resultant string is stored in str1. strcat(str1, str2); printf("String 1=%s", str1); printf("\nString 2=%s", str2); return 0; } 19 String Operations without using String library functions 1. Copy String without using strcpy() Loops can be used to copy a String without using the strcpy() function. Here one string is given as input then with the help of for loop, the content of the first array is transfer to the second array. If the destination string length is less than the source string, the entire string value won’t be copied into the destination string. For example, consider the destination string length is 20 and the source string length is 30. Then, only 20 characters from the source string will be copied into the destination, and the remaining 10 characters will be truncated 20 Example: Copy String without using strcpy() #include s2[i] = '\0'; int main() { // s1 is the source( input) string and // printing the destination string // s2 is the destination string printf("String s2 : %s", s2); return 0; char s1[] = “WelcomeSSBT", s2, i; } // Print the string s1 printf("string s1 : %s\n", s1); for (i = 0; s1[i] != '\0'; ++i) { s2[i] = s1[i]; } 21 2. Find length of string without using strlen( ) #include Output: int main() Enter a string: SSBT { char str; Length of input string: 4 int i, length=0; printf("Enter a string: \n"); scanf("%s",str); for(i=0; str[i]!='\0'; i++) { length++; } printf("\n Length of input string: %d", length); return 0; } 22 Structure 23 Why use Structures? In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has all the information of one type only. It can have different attributes of different data types. For example, an entity Student may have its name (string), roll number (int), marks (float). To store such type of information regarding an entity student, we have the following approaches: Construct individual arrays for storing names, roll numbers, and marks. Use a special data structure to store the collection of different data types. 24 Structures Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. 25 Declaring a Structure The ,struct keyword is used to define the structure. Syntax: Example: struct structure_name struct employee { data_type member1; { int id; data_type member2; char name;.. float salary; data_type memeberN; }; }; 26 How Structure Elements are Stored? The memory allocation of the structure employee that is defined in the above example is shown below:. 27 Creating structure variable We can declare a variable for the structure so that we can access the member of the structure easily. There are two ways to declare structure variable: 1.By struct keyword within main() function struct employee { int id; char name; float salary; }; Now write given code inside the main() function. struct employee e1, e2; 28 Creating structure variable 2. By declaring a variable at the time of defining the structure. struct employee { int id; char name; float salary; }e1,e2; 29 Accessing Structure Elements To access the structure members, we have to use member operator or dot operator (.) Suppose user want to access the id member of p1 variable by. (member) operator. p1.id 30 Example 1 strcpy(e1.name, “Shital Patel"); #include //copying string into char array #include //printing first employee information struct employee printf( "employee 1 id : %d\n", e1.id); { int id; printf( "employee 1 name : %s\n", e1.name); char name; return 0; }e1; //declaring e1 variable for structure int main( ) } { Output: //store first employee information e1.id=101; employee 1 id : 101 employee 1 name : Shital Patel 31 Example 2 strcpy(b1.bookname, “Let us C”); #include //copying string into char array #include //printing first employee information struct book { int pages; printf( “Book 1 pages : %d\n", b1.pages); printf( “Book 1 price : %f\n", b1.price); float price; printf( “Book 1 name : %s\n", b1.bookname); char bookname; return 0; }b1; //declaring b1 variable for structure } int main( ) { //store first employee information Output: b1.pages=101; Book 1 pages : 101 b1.price=125.50; Book 1 price : 125.50 Book 1 name : Let us C 32 Array of Structure An array of structures in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. The array of structures in C are used to store information about multiple entities of different data types. The array of structures is also known as the collection of structures. 33 34 Example of an array of structures that stores information of 5 students and prints it. #include printf("\nEnter Rollno:"); #include scanf("%d",&st[i].rollno); struct student{ printf("\nEnter Name:"); int rollno; scanf("%s",&st[i].name); } char name; printf("\nStudent Information List:"); }; for(i=0;i

Use Quizgecko on...
Browser
Browser