Unit-3 String- C Programming | BCA 2nd Sem
Unit-3 String- C Programming | BCA 2nd Sem- Hello everyone welcome to the pencilchampions.com website. This website provide Unit-3 String- C Programming | BCA 2nd Sem CCS University Notes. Thankyou for visiting.
Unit-3
String
Meaning of Strings
- A string is a group of characters that are enclosed in double quotes. It is used to represent text or words in a program. Strings in C are actually arrays of characters, where each character is stored in a consecutive memory location. The last character of a string is always a null character (‘\0’), which marks the end of the string.
- Strings in C can be manipulated using various functions, such as strlen() to get the length of a string, strcpy() to copy one string to another, strcat() to concatenate two strings, and strcmp() to compare two strings. You can also access individual characters in a string using array indexing.
- It’s important to remember that in C, strings are immutable, which means that once a string is created, its contents cannot be changed directly. If you want to modify a string, you’ll need to create a new string with the desired changes.
- Strings are widely used in C programming for tasks like input/output operations, text processing, and storing data. They are an essential part of C programming and understanding how to work with strings is crucial for writing effective programs.
Read more-Â https://pencilchampions.com/unit-2-pointers-c-programming-bca-2nd-sem/
Declaration of String
- We declare a string by using the array notation. We define an array of characters and initialize it with the desired string. Here’s an example:
C
char myString[] = “Hello, World!”;
- In this example, we declare a string named myString and initialize it with the text “Hello, World!”. The char keyword is used to specify that each element of the array is a character. The square brackets [] indicate that myString is an array. The size of the array is determined automatically based on the length of the string.
- Alternatively, we can also declare a string by specifying its size explicitly. Here’s an example:
Wikipedia-Â https://en.wikipedia.org/wiki/C_string_handling
C
char myString[20] = “Hello, World!”;
- In this case, we declare myString as an array of characters with a size of 20. This means that it can hold up to 19 characters, leaving one space for the null character that marks the end of the string.
- It’s important to note that in C, strings are null-terminated, meaning that they end with a null character (‘\0’). The null character is automatically added to the end of the string when we initialize it with a string literal.
- We can also declare an empty string and later assign a value to it using string manipulation functions. Here’s an example:
C
char myString[50];
strcpy(myString, “Hello, World!”);
- In this case, we declare myString as an array of characters with a size of 50. Then, we use the strcpy() function to copy the string “Hello, World!” into myString.
- Remember that when declaring strings, it’s important to ensure that the size of the array is large enough to accommodate the string and the null character. Otherwise, it may lead to buffer overflow and unexpected behavior.
Initializing of String
- To initialize a string (character array) in C, you can use either of the following methods:
- Initializing at the time of declaration:
C
  char myString[] = “Hello, World!”;
- In this method, the size of the array is automatically determined based on the length of the string literal. The null character (‘\0’) is automatically added at the end.
- Initializing with a specific size:
C
  char myString[20] = “Hello, World!”;
- Here, the size of the array is explicitly specified as 20. It should be large enough to accommodate the string and the null character.
- Initializing an empty string and assigning a value later:
C
  char myString[50];
  strcpy(myString, “Hello, World!”);
- In this case, we declare the array without initializing it. Later, we can use the strcpy() function to copy a string into the array.
- Remember that strings in C are null-terminated, meaning they end with a null character (‘\0’).
Standard library function
- In the C programming language, there is a wide range of standard library functions available for various purposes. These functions are already defined in the standard C library and provide ready-to-use functionality without the need for us to write the code from scratch. Let’s take a look at some commonly used standard library functions in C:
- Input/Output Functions:
- printf(): Used to print formatted output to the console.
- scanf(): Used to read formatted input from the console.
- getchar(): Reads a single character from the console.
- String Manipulation Functions:
- strlen(): Calculates the length of a string.
- strcpy(): Copies one string to another.
- strcat(): Concatenates two strings.
- strcmp(): Compares two strings.
- Mathematical Functions:
- sqrt(): Calculates the square root of a number.
- pow(): Raises a number to a specified power.
- abs(): Returns the absolute value of a number.
- Memory Management Functions:
- malloc(): Allocates a block of memory dynamically.
- calloc(): Allocates a block of memory and initializes it to zero.
- realloc(): Changes the size of a previously allocated block of memory.
- free(): Releases the memory allocated by malloc, calloc, or realloc.
- File Handling Functions:
- fopen(): Opens a file.
- fclose(): Closes a file.
- fprintf(): Writes formatted output to a file.
- fscanf(): Reads formatted input from a file.
- These are just a few examples of the many standard library functions available in C. Each function serves a specific purpose and can be very useful in simplifying our programming tasks. It’s always a good idea to refer to the C documentation or a good C programming book for a comprehensive list of standard library functions and their usage.
- Strlen() Function
- The strlen() function in C is used to calculate the length of a string. It takes a string as input and returns the number of characters in the string, excluding the null character (‘\0’) at the end.
- Here’s an example of how to use the strlen() function:
C
#include <stdio.h>
#include <string.h>
int main() {
   char str[] = “Hello, World!”;
   int length = strlen(str);
   printf(“The length of the string is: %d\n”, length);
   return 0;
}
- In this example, we include the <string.h> header file, which contains the declaration of the strlen() function. We declare a character array str and initialize it with the string “Hello, World!”. Then, we use the strlen() function to calculate the length of the string and store it in the length variable. Finally, we print the length of the string using printf().
Program to demonstrate strlen() Function
Strcpy() Function
- The strcpy() function in C is used to copy one string to another. It takes two arguments: the destination string and the source string. The destination string should have enough space to hold the source string.
Here’s an example of how to use the strcpy() function:
C
#include <stdio.h>
#include <string.h>
int main() {
   char source[] = “Hello, World!”;
   char destination[20];
   strcpy(destination, source);
   printf(“The copied string is: %s\n”, destination);
   return 0;
}
- In this example, we include the <string.h> header file, which contains the declaration of the strcpy() function. We declare a source string source and initialize it with the string “Hello, World!”. We also declare a destination string destination with enough space to hold the source string.
- We then use the strcpy() function to copy the source string to the destination string. The destination string will now contain the same characters as the source string.
Strcat() Function
- The strcat() function in C is used to concatenate (or join) two strings together. It takes two arguments: the destination string and the source string. The destination string should have enough space to hold both strings.
Here’s an example of how to use the strcat() function:
C
#include <stdio.h>
#include <string.h>
int main() {
   char destination[20] = “Hello, “;
   char source[] = “World!”;
   strcat(destination, source);
   printf(“The concatenated string is: %s\n”, destination);
   return 0;
}
- In this example, we declare a destination string destination with enough space to hold both strings. We initialize it with the string “Hello, “. We also declare a source string source with the string “World!”.
- We then use the strcat() function to concatenate the source string to the destination string. The destination string will now contain “Hello, World!”.
Strcmp() Function
- The strcmp() function in C is used to compare two strings. It returns an integer value based on the lexicographical comparison of the strings.
Here’s an example of how to use the strcmp() function:
C
#include <stdio.h>
#include <string.h>
int main() {
   char string1[] = “apple”;
   char string2[] = “banana”;
   int result = strcmp(string1, string2);
   if (result < 0) {
       printf(“String 1 is less than String 2\n”);
   } else if (result > 0) {
       printf(“String 1 is greater than String 2\n”);
   } else {
       printf(“String 1 is equal to String 2\n”);
   }
   return 0;
}
- In this example, we have two strings: string1 and string2. We use the strcmp() function to compare the two strings.
- If the result is less than 0, it means that string1 is less than string2. If the result is greater than 0, it means that string1 is greater than string2. If the result is 0, it means that string1 is equal to string2.
- In the example above, since “apple” comes before “banana” in lexicographical order, the output will be:
String 1 is less than String 2
Implementation without using standard library function
Calculate the Length of String without Using strlen() Function
- To calculate the length of a string without using the strlen() function, you can iterate through the characters of the string until you reach the null character (‘\0’) that marks the end of the string.
Here’s an example implementation in C:
C
#include <stdio.h>
int stringLength(char* str) {
   int length = 0;
   while (str[length] != ‘\0’) {
       length++;
   }
   return length;
}
int main() {
   char string[] = “Hello, world!”;
   int length = stringLength(string);
   printf(“The length of the string is: %d\n”, length);
   return 0;
}
- In this example, we define a function stringLength() that takes a pointer to a character array (string) as an argument. Inside the function, we initialize a variable length to 0. We then iterate through the characters of the string using a while loop, incrementing the length variable until we encounter the null character (‘\0’).
- Finally, in the main() function, we declare a string and pass it to the stringLength() function to calculate its length. We then print the result.
The output of this program will be:
The length of the string is: 13
C Program to copy one string into Other Without using Library function
C
#include <stdio.h>
void stringCopy(char* source, char* destination) {
   int i = 0;
   while (source[i] != ‘\0’) {
       destination[i] = source[i];
       i++;
   }
   destination[i] = ‘\0’;
}
int main() {
   char source[] = “Hello, world!”;
   char destination[20];
   stringCopy(source, destination);
   printf(“Copied string: %s\n”, destination);
   return 0;
}
- In this example, we define a function stringCopy() that takes two arguments: source and destination, which are pointers to character arrays. Inside the function, we use a while loop to iterate through the characters of the source string and copy them one by one into the destination string. We terminate the destination string with a null character (‘\0’) to mark the end of the string.
- In the main() function, we declare a source string and an empty destination string. We then call the stringCopy() function, passing the source and destination strings as arguments. After the function call, we print the destination string to verify that the copy was successful.
The output of this program will be:
Copied string: Hello, world!
Discover more from Pencil Champions
Subscribe to get the latest posts sent to your email.