The document discusses various topics related to arrays, strings, and string handling functions in C programming language. It explains that arrays are collections of variables of the same type that can be accessed using indexes. One-dimensional and multi-dimensional arrays are declared along with examples. Common string functions like strlen(), strcpy(), strcat() etc. are described with examples to manipulate strings in C. Pointers and their usage with arrays and strings are also covered briefly.
Arrays in C allow storing multiple values of the same data type in contiguous memory locations. An array is declared with a data type, array name, and size. Individual elements are accessed using the array name and index. Arrays are useful for storing lists of values, performing matrix operations, implementing algorithms like search and sort, and more. Strings in C are implemented as arrays of characters that are null-terminated. Functions like strcpy(), strcat(), strcmp() allow manipulating strings.
The document discusses arrays and strings in C programming. It covers key topics like:
- Declaring and initializing arrays and accessing array elements. Arrays have 0 as the first index.
- Difference between initialization and assignment of arrays. Arrays cannot be assigned.
- String arrays which are arrays of characters terminated by a null character.
- Common string functions like strcpy(), strcat(), strlen(), strcmp() etc.
- Two dimensional arrays and how elements are stored in row major order in contiguous memory.
- Examples of declaring, initializing and accessing 2D arrays.
Arrays allow storing of a collection of related data under a single variable name. There are different types of arrays including one-dimensional, two-dimensional, and multi-dimensional arrays. One-dimensional arrays use a single subscript, two-dimensional arrays use two subscripts for rows and columns, and multi-dimensional arrays can use more than two subscripts. Arrays in C can be initialized at compile-time or run-time. Common operations on arrays include reading and writing elements, concatenation, comparison and more. C provides functions like strlen(), strcat(), strcmp() for string handling and manipulation.
The document discusses strings in C programming. It defines strings as sequences of characters stored as character arrays that are terminated with a null character. It covers string literals, declaring and initializing string variables, reading and writing strings, and common string manipulation functions like strlen(), strcpy(), strcmp(), and strcat(). These functions allow operations on strings like getting the length, copying strings, comparing strings, and concatenating strings.
An array is a collection of similar data types stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, float, etc. Elements of an array are accessed using indexes and they are stored sequentially in memory. Strings in C are arrays of characters terminated by a null character. Common functions to manipulate strings include strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().
This document discusses strings in C programming. It defines strings as arrays of characters that end with a null terminator (\0). It explains how to initialize and print strings. Common string functions like strlen(), strcpy(), strcat(), and strcmp() are described. The document contrasts strings and character pointers, noting strings cannot be reassigned while pointers can. Finally, it lists and briefly explains other standard string library functions.
Diploma ii cfpc u-4 function, storage class and array and stringsRai University
The document discusses various aspects of arrays and functions in C programming language. It explains that arrays allow storing multiple elements of the same type using a single name. One-dimensional and multi-dimensional arrays are described along with initialization and accessing of array elements. Common string handling functions like strcat(), strcmp(), strcpy() are also summarized. The document also provides the general forms of defining and calling functions in C and different categories of functions based on arguments and return values.
C programming language provides arrays as a data structure to store a fixed-size collection of elements of the same type. An array stores elements in contiguous memory locations. Individual elements in an array can be accessed using an index. Common array operations in C include declaration, initialization, accessing and modifying individual elements, and passing arrays to functions.
Btech i pic u-4 function, storage class and array and stringsRai University
Arrays allow storing multiple values of the same type under a common name. One-dimensional arrays use a single subscript to access elements, while multi-dimensional arrays use multiple subscripts. Strings are arrays of characters terminated by a null character. Functions allow breaking programs into modular reusable units. Functions can take arguments, return values, or do both. Variables declared inside functions have automatic storage, while those outside have external storage. Arrays and strings can be passed to functions. Recursion occurs when a function calls itself.
Functions torage class and array and strings-aneebkmct
Arrays allow storing multiple values of the same type under a common name. One-dimensional arrays use a single subscript to access elements, while multi-dimensional arrays use multiple subscripts. Strings are arrays of characters terminated by a null character. Functions allow breaking programs into smaller, reusable parts. Functions can accept arguments, return values, or have no arguments and return nothing. Variables declared inside functions have automatic storage, while those outside have external storage.
function, storage class and array and stringsRai University
The document discusses one-dimensional arrays in C programming. It defines arrays, explains how to declare and initialize them, and provides examples of accessing array elements. It also discusses reading and printing arrays, and summarizes common string handling functions in C like strcat(), strcmp(), and strcpy().
1. Arrays allow storing of multiple elements of the same data type under a single name. They can be one-dimensional, two-dimensional, or multi-dimensional. Strings are arrays of characters terminated by a null character.
2. Common array operations include declaring and initializing arrays, accessing elements using indexes, and performing element-by-element operations. Strings have specialized functions for operations like length calculation, copying, comparison and concatenation.
3. Pointers allow working with arrays by reference rather than value and are useful for passing arrays to functions. Structures group together different data types under one name and unions allow storing different data types in the same memory space.
Bsc cs i pic u-4 function, storage class and array and stringsRai University
The document discusses arrays and functions in C programming. It defines arrays as groups of related data items that share a common name. One-dimensional and multi-dimensional arrays are described. Functions are defined as reusable blocks of code that can take input arguments and return values. The key elements of functions like return values, arguments, and function calls are explained. Common string handling and mathematical functions are also summarized.
Mcai pic u 4 function, storage class and array and stringsRai University
Arrays allow storing multiple values of the same type under a common name. One-dimensional arrays use a single subscript to access elements, while multi-dimensional arrays use multiple subscripts. Strings are arrays of characters that end with a null character. Functions allow breaking programs into smaller, reusable parts. Functions can take arguments, return values, or do both. Variables declared inside functions have automatic storage, while those outside have external storage. Arrays and strings can be passed to functions. Recursion occurs when a function calls itself.
The document discusses arrays and string operations in C programming. It defines arrays as structures that hold related data items of the same type. It covers one-dimensional and two-dimensional arrays, including declaring, initializing, accessing, and manipulating array elements. It also defines strings as sequences of characters stored as character arrays terminated with a null character. It discusses string declaration, input/output, and standard library functions for determining string length and manipulating strings.
This document discusses handling of character strings in C programming. It covers declaring and initializing string variables as character arrays, reading strings from the terminal using scanf() and gets(), writing strings to the screen using printf() and puts(), performing arithmetic operations and comparisons on characters, concatenating strings, and commonly used string handling functions like strcpy(), strcat(), and strcmp().
This document discusses handling of character strings in C. It explains that a string is a sequence of characters stored in memory as ASCII codes appended with a null terminator. It describes common string operations in C like reading, displaying, concatenating, comparing and extracting substrings. It also discusses functions like strlen(), strcat(), strcmp(), strcpy() for performing various operations on strings.
Arrays & Strings can be summarized as follows:
1. Arrays are fixed-size collections of elements of the same data type that are used to store lists of related data. They can be one-dimensional, two-dimensional, or multi-dimensional.
2. Strings in C are arrays of characters terminated by a null character. They are commonly used to store text data. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings.
3. Arrays are declared with a data type, name, and size. They can be initialized with a block of comma-separated values. Individual elements are accessed using indexes in square brackets. Two-dimensional arrays represent tables
An array is a collection of similar data types stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, float, etc. Elements of an array are accessed using indexes and they are stored sequentially in memory. Strings in C are arrays of characters terminated by a null character. Common functions to manipulate strings include strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().
This document discusses strings in C programming. It defines strings as arrays of characters that end with a null terminator (\0). It explains how to initialize and print strings. Common string functions like strlen(), strcpy(), strcat(), and strcmp() are described. The document contrasts strings and character pointers, noting strings cannot be reassigned while pointers can. Finally, it lists and briefly explains other standard string library functions.
Diploma ii cfpc u-4 function, storage class and array and stringsRai University
The document discusses various aspects of arrays and functions in C programming language. It explains that arrays allow storing multiple elements of the same type using a single name. One-dimensional and multi-dimensional arrays are described along with initialization and accessing of array elements. Common string handling functions like strcat(), strcmp(), strcpy() are also summarized. The document also provides the general forms of defining and calling functions in C and different categories of functions based on arguments and return values.
C programming language provides arrays as a data structure to store a fixed-size collection of elements of the same type. An array stores elements in contiguous memory locations. Individual elements in an array can be accessed using an index. Common array operations in C include declaration, initialization, accessing and modifying individual elements, and passing arrays to functions.
Btech i pic u-4 function, storage class and array and stringsRai University
Arrays allow storing multiple values of the same type under a common name. One-dimensional arrays use a single subscript to access elements, while multi-dimensional arrays use multiple subscripts. Strings are arrays of characters terminated by a null character. Functions allow breaking programs into modular reusable units. Functions can take arguments, return values, or do both. Variables declared inside functions have automatic storage, while those outside have external storage. Arrays and strings can be passed to functions. Recursion occurs when a function calls itself.
Functions torage class and array and strings-aneebkmct
Arrays allow storing multiple values of the same type under a common name. One-dimensional arrays use a single subscript to access elements, while multi-dimensional arrays use multiple subscripts. Strings are arrays of characters terminated by a null character. Functions allow breaking programs into smaller, reusable parts. Functions can accept arguments, return values, or have no arguments and return nothing. Variables declared inside functions have automatic storage, while those outside have external storage.
function, storage class and array and stringsRai University
The document discusses one-dimensional arrays in C programming. It defines arrays, explains how to declare and initialize them, and provides examples of accessing array elements. It also discusses reading and printing arrays, and summarizes common string handling functions in C like strcat(), strcmp(), and strcpy().
1. Arrays allow storing of multiple elements of the same data type under a single name. They can be one-dimensional, two-dimensional, or multi-dimensional. Strings are arrays of characters terminated by a null character.
2. Common array operations include declaring and initializing arrays, accessing elements using indexes, and performing element-by-element operations. Strings have specialized functions for operations like length calculation, copying, comparison and concatenation.
3. Pointers allow working with arrays by reference rather than value and are useful for passing arrays to functions. Structures group together different data types under one name and unions allow storing different data types in the same memory space.
Bsc cs i pic u-4 function, storage class and array and stringsRai University
The document discusses arrays and functions in C programming. It defines arrays as groups of related data items that share a common name. One-dimensional and multi-dimensional arrays are described. Functions are defined as reusable blocks of code that can take input arguments and return values. The key elements of functions like return values, arguments, and function calls are explained. Common string handling and mathematical functions are also summarized.
Mcai pic u 4 function, storage class and array and stringsRai University
Arrays allow storing multiple values of the same type under a common name. One-dimensional arrays use a single subscript to access elements, while multi-dimensional arrays use multiple subscripts. Strings are arrays of characters that end with a null character. Functions allow breaking programs into smaller, reusable parts. Functions can take arguments, return values, or do both. Variables declared inside functions have automatic storage, while those outside have external storage. Arrays and strings can be passed to functions. Recursion occurs when a function calls itself.
The document discusses arrays and string operations in C programming. It defines arrays as structures that hold related data items of the same type. It covers one-dimensional and two-dimensional arrays, including declaring, initializing, accessing, and manipulating array elements. It also defines strings as sequences of characters stored as character arrays terminated with a null character. It discusses string declaration, input/output, and standard library functions for determining string length and manipulating strings.
This document discusses handling of character strings in C programming. It covers declaring and initializing string variables as character arrays, reading strings from the terminal using scanf() and gets(), writing strings to the screen using printf() and puts(), performing arithmetic operations and comparisons on characters, concatenating strings, and commonly used string handling functions like strcpy(), strcat(), and strcmp().
This document discusses handling of character strings in C. It explains that a string is a sequence of characters stored in memory as ASCII codes appended with a null terminator. It describes common string operations in C like reading, displaying, concatenating, comparing and extracting substrings. It also discusses functions like strlen(), strcat(), strcmp(), strcpy() for performing various operations on strings.
Arrays & Strings can be summarized as follows:
1. Arrays are fixed-size collections of elements of the same data type that are used to store lists of related data. They can be one-dimensional, two-dimensional, or multi-dimensional.
2. Strings in C are arrays of characters terminated by a null character. They are commonly used to store text data. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings.
3. Arrays are declared with a data type, name, and size. They can be initialized with a block of comma-separated values. Individual elements are accessed using indexes in square brackets. Two-dimensional arrays represent tables
Linked Lists: A Comprehensive Guide Advantages, various types, and fundamenta...MSridhar18
Welcome to our exploration of Linked Lists! This presentation will introduce you to
the fundamentals of linked lists, including their advantages, various types, and
fundamental operations.
Data Structures: A Foundation for Efficient ProgrammingMSridhar18
Welcome to our journey into the world of data structures. Today, we'll explore the fundamental concepts, classification, and practical applications of these essential programming tools.
Research Handbook On Environment And Investment Law Kate Milesmucomousamir
Research Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate Miles
Research Handbook On Environment And Investment Law Kate Miles
Order: Odonata Isoptera and Thysanoptera.pptxArshad Shaikh
*Odonata*: Odonata is an order of insects that includes dragonflies and damselflies. Characterized by their large, compound eyes and agile flight, they are predators that feed on other insects, playing a crucial role in maintaining ecological balance.
*Isoptera*: Isoptera is an order of social insects commonly known as termites. These eusocial creatures live in colonies with complex social hierarchies and are known for their ability to decompose wood and other cellulose-based materials, playing a significant role in ecosystem nutrient cycling.
*Thysanoptera*: Thysanoptera, or thrips, are tiny insects with fringed wings. Many species are pests that feed on plant sap, transmitting plant viruses and causing damage to crops and ornamental plants. Despite their small size, they have significant impacts on agriculture and horticulture.
Paper 110A | Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr...Rajdeep Bavaliya
Dive into the haunting worlds of German Expressionism as we unravel how shadows and light elevate ‘The Cabinet of Dr. Caligari’ and ‘Nosferatu: A Symphony of Horror’ into timeless masterpieces. Discover the psychological power of chiaroscuro, distorted sets, and evocative silhouettes that shaped modern horror. Whether you’re a film buff or a budding cinephile, this journey through post‑WWI trauma and surreal visuals will leave you seeing movies in a whole new light. Hit play, share your favorite shock‑and‑awe moment in the comments, and don’t forget to follow for more deep‑dives into cinema’s most influential movements!
M.A. Sem - 2 | Presentation
Presentation Season - 2
Paper - 110A: History of English Literature – From 1900 to 2000
Submitted Date: April 1, 2025
Paper Name: History of English Literature – From 1900 to 2000
Topic: Shadows and Light: Exploring Expressionism in ‘The Cabinet of Dr. Caligari’ and ‘Nosferatu: A Symphony of Horror’
[Please copy the link and paste it into any web browser to access the content.]
Video Link: https://youtu.be/pWjHqo6clT4
For a more in-depth discussion of this presentation, please visit the full blog post at the following link:
Please visit this blog to explore additional presentations from this season:
Hashtags:
#GermanExpressionism #SilentHorror #Caligari #Nosferatu #Chiaroscuro #VisualStorytelling #FilmHistory #HorrorCinema #CinematicArt #ExpressionistAesthetics
Keyword Tags:
Expressionism, The Cabinet of Dr. Caligari, Nosferatu, silent film horror, film noir origins, German Expressionist cinema, chiaroscuro techniques, cinematic shadows, psychological horror, visual aesthetics
How to Use Owl Slots in Odoo 17 - Odoo SlidesCeline George
In this slide, we will explore Owl Slots, a powerful feature of the Odoo 17 web framework that allows us to create reusable and customizable user interfaces. We will learn how to define slots in parent components, use them in child components, and leverage their capabilities to build dynamic and flexible UIs.
How to Setup Renewal of Subscription in Odoo 18Celine George
A subscription is a recurring plan where you set a subscription period, such as weekly, monthly, or yearly. Based on this period, the subscription renews automatically. In Odoo 18, you have the flexibility to manage renewals either manually or automatically.
"Orthoptera: Grasshoppers, Crickets, and Katydids pptxArshad Shaikh
Orthoptera is an order of insects that includes grasshoppers, crickets, and katydids. Characterized by their powerful hind legs, Orthoptera are known for their impressive jumping ability. With diverse species, they inhabit various environments, playing important roles in ecosystems as herbivores and prey. Their sounds, often produced through stridulation, are distinctive features of many species.
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesCeline George
The Lunch module in Odoo 18 helps users place their food orders, making meal management seamless and efficient. It allows employees to browse available options, place orders, and track their meals effortlessly.
This study describe how to write the Research Paper and its related issues. It also presents the major sections of Research Paper and various tools & techniques used for Polishing Research Paper
before final submission.
Finding a Right Journal and Publication Ethics are explain in brief.
Principal Satbir Singh writes “Kaba and Kitab i.e. Building Harmandir Sahib and Compilation of Granth Sahib gave Sikhs a central place of worship and a Holy book is the single most important reason for Sikhism to flourish as a new religion which gave them a identity which was separate from Hindu’s and Muslim’s.
Students will research and orally present a Colombian company using a visual tool, in order to develop their communication skills and intercultural understanding through the exploration of identity, innovation, and local culture, in connection with the IB global themes.
How to Add a Custom Menu, List view and FIlters in the Customer Portal Odoo 18Celine George
To create a new menu in the "My Accounts" portal and set up a list/form view in Odoo 18, follow these steps. For Example- The custom menu has now been added to the "Fleet" customer portal.
How to Configure Subcontracting in Odoo 18 ManufacturingCeline George
Subcontracting in manufacturing involves outsourcing specific production tasks to external vendors or subcontractors. These tasks may include manufacturing certain components, handling assembly processes, or even producing entire product lines.
The PDF titled "Critical Thinking and Bias" by Jibi Moses aims to equip a diverse audience from South Sudan with the knowledge and skills necessary to identify and challenge biases and stereotypes. It focuses on developing critical thinking abilities and promoting inclusive attitudes to foster a more cohesive and just society. It defines bias as a tendency or prejudice affecting perception and interactions, categorizing it into conscious and unconscious (implicit) biases. The content highlights the impact of societal and cultural conditioning on these biases, particularly within the South Sudanese context.
Order Lepidoptera: Butterflies and Moths.pptxArshad Shaikh
Lepidoptera is an order of insects comprising butterflies and moths. Characterized by scaly wings and a distinct life cycle, Lepidoptera undergo metamorphosis from egg to larva (caterpillar) to pupa (chrysalis or cocoon) and finally to adult. With over 180,000 described species, they exhibit incredible diversity in form, behavior, and habitat, playing vital roles in ecosystems as pollinators, herbivores, and prey. Their striking colors, patterns, and adaptations make them a fascinating group for study and appreciation.
2. Introduction to
Array:
What is an Array?
An array in C is a collection of similar data types stored in contiguous memory locations. It's
a fundamental data structure used to store multiple values under a single name.
Declaring an Array
To declare an array, you specify the data type, array name, and size:
Syntax:
data_type array_name[size];
Example:
int numbers[5];
3. One Dimentional
Array:
A one-dimensional array is a linear collection of elements of the same data type, stored in
contiguous memory locations. It's like a row of containers, each holding a value of the same
type.
Declaring a One-Dimensional Array
Syntax:
data_type array_name[size];
• data_type: The data type of the elements (e.g., int, float, char).
• array_name: The name of the array.
• size: The number of elements in the array.
4. Accessing Array Elements:
To access an element, use its index within square brackets:
Syntax:
array_name[index]
• index: The position of the element (starts from 0).
Example:
numbers[2] = 30;
Initializing an Array:
You can initialize an array while declaring it:
Syntax:
data_type array_name[size] = {value1, value2, ..., valueN};
Example:
int marks[5] = {85, 92, 78, 95, 88};
5. Example Program for one dimentional array:
#include <stdio.h>
int main() {
int numbers[5] = {2, 4, 6, 8, 10};
int i;
// Accessing and printing array elements
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
6. Two Dimentional
Array:
Declaring a Two-Dimensional Array
syntax:
data_type array_name[rows][columns];
Example:
int matrix[3][4];
A two-dimensional array is essentially an array of arrays. It can be visualized as a matrix with
rows and columns. Each element in the array is identified by two indices: one for the row and
one for the column.
7. Accessing Array Elements:
To access an element, use two indices:
Syntax:
array_name[row][column];
Example:
matrix[1][2] = 10;
Initializing a Two-Dimensional Array
You can initialize a two-dimensional array while declaring it:
Syntax:
data_type array_name[rows][columns] = {{value11, value12, ...},
{value21, value22, ...},
...};
Example:
int numbers[2][3] = {{1, 2, 3}, {4, 5, 6}};
8. Example Program
#include <stdio.h>
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int i, j;
// Accessing and printing array elements
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("n");
}
return 0;
}
9. Multidimensional
Array:
A multidimensional array is an extension of the concept of a one-dimensional array. It's essentially
an array of arrays, allowing you to store data in a tabular or grid-like structure.
Declaring a Multidimensional Array:
Syntax:
data_type array_name[size1][size2][...][sizeN];
Example:
int matrix[3][4];
Accessing Array Elements
To access an element, use multiple indices separated by commas:
Syntax:
array_name[index1][index2][...][indexN]
Example:
matrix[1][2] = 10;
10. Initializing a Multidimensional Array
You can initialize a multidimensional array while declaring it:
Syntax:
data_type array_name[size1][size2] = {{value11, value12, ...},
{value21, value22, ...},
Example:
int numbers[2][3] = {{1, 2, 3}, {4, 5, 6}};
...};
11. Example Program (3D Array)
#include <stdio.h>
int main() {
int cube[2][3][2] = {{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}};
int i, j, k;
// Accessing and printing array elements
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
for (k = 0; k < 2; k++) {
printf("%d ", cube[i][j][k]);
}
printf("n");
}
printf("n");
}
return 0;
}
12. Character Array and
String:
Character Arrays
A character array in C is simply an array of characters. It's a fundamental building block for
handling text data.
Declaration:
char char_array[size];
• size: The maximum number of characters the array can hold.
Example:
char message[10] = "Hello";
13. String:
Strings
In C, a string is essentially a character array with a null character ('0') at the end to mark its
termination. This allows functions to determine the length of the string without explicitly
storing it.
Key points:
• Strings are implicitly null-terminated.
• You can use string manipulation functions from the string.h library.
Example:
char greeting[] = "Welcome";
14. Initializing String Variables in C
In C, strings are essentially character arrays with a null terminator (0) at the end. There are
primarily two methods to initialize a string variable:
1. Direct Initialization
Example:
char str[] = "Hello, world!"
2. Explicit Initialization
Example:
char str[14] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '0'};
16. Reading Strings from the Terminal:
Using scanf()
The scanf() function can be used to read a string from the standard input (terminal). However,
it has limitations: it stops reading at the first whitespace character (space, tab, newline).
Example:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %sn", str);
return 0;
}
17. Using fgets()
The fgets() function is a safer and more flexible way to read a string, including whitespace
characters. It reads a specified number of characters or until a newline character is
encountered.
Example:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
printf("You entered: %s", str);
return 0;
}
18. Writing String to Screen:
Using printf()
The most common way to write a string to the screen in C is using the printf() function.
Example:
#include <stdio.h>int main() {
char str[] = "Hello, world!";
printf("%sn", str);
return 0;
}
Using puts()
Another option is the puts() function, which is specifically designed for writing strings to the standard output.
Example:
#include <stdio.h>int main() {
char str[] = "Hello, world!";
puts(str);
return 0;
}
19. Comparing Strings in C
Using the strcmp() Function
The most common and efficient way to compare strings in C is by using the strcmp() function
from the string.h library.
Syntax:
int strcmp(const char *str1, const char *str2);
Manual String Comparison
While strcmp() is generally preferred, you can also compare strings manually by iterating
through characters and comparing them individually. This approach can be useful for specific
scenarios or learning purposes.
20. Example Program:
#include <stdio.h>
int compare_strings(const char *str1, const char *str2) {
while (*str1 != '0' && *str2 != '0') {
if (*str1 != *str2) {
return *str1 - *str2; // Return difference in ASCII values
}
str1++;
str2++;
}
return *str1 - *str2; // Compare lengths if strings are equal up to this point
}
21. int main() {
char str1[] = "hello";
char str2[] = "world";
int result = compare_strings(str1, str2);
if (result == 0) {
printf("Strings are equaln");
} else {
printf("Strings are not equaln");
}
return 0;
}
22. String Handling Functions in C
C provides a rich set of functions for manipulating strings. These functions are primarily
defined in the string.h header file.
Common String Handling Functions
Here are some of the most commonly used string handling functions in C:
Length of a String
• strlen(str): Returns the length of a string (excluding the null terminator).
Copying Strings
• strcpy(dest, src): Copies the string src to the destination string dest. Be cautious about
buffer overflows.
• strncpy(dest, src, n): Copies at most n characters from src to dest.
Concatenating Strings
• strcat(dest, src): Appends src to the end of dest. Be careful about buffer overflows.
• strncat(dest, src, n): Appends at most n characters from src to dest.
23. Comparing Strings
• strcmp(str1, str2): Compares two strings lexicographically. Returns 0 if equal, a negative value
if str1 is less than str2, and a positive value if str1 is greater than str2.
• strncmp(str1, str2, n): Compares at most n characters of str1 and str2.
Searching in Strings
• strchr(str, ch): Finds the first occurrence of character ch in string str.
• strrchr(str, ch): Finds the last occurrence of character ch in string str.
• strstr(str1, str2): Finds the first occurrence of string str2 in string str1.
Converting Case
• tolower(ch): Converts a character to lowercase.
• toupper(ch): Converts a character to uppercase.
Other Useful Functions
• strtok(str, delimiters): Breaks a string into tokens based on delimiters.
• memset(str, ch, n): Fills a block of memory with a specific character.
• memcpy(dest, src, n): Copies a block of memory from src to dest.
24. Example Program
#include <stdio.h>#include <string.h>int main() {
char str1[] = "hello";
char str2[20];
strcpy(str2, str1);
strcat(str2, " world");
printf("%sn", str2);
if (strcmp(str1, "hello") == 0) {
printf("Strings are equaln");
}
char *ptr = strchr(str2, 'o');
if (ptr) {
printf("First occurrence of 'o': %sn", ptr);
}
return 0;
}