pre defined str function in c

27 Sep 2022 Balmiki Mandal 0 C Programming

In C, a pre-defined string (also called a string literal) is a sequence of characters enclosed in double-quotes. For example, "Hello, World!" is a pre-defined string in C.

When a pre-defined string is used in a C program, it is automatically converted to an array of characters that represents the string. The terminating null character '\0' is also included in the array.

Here's an example of how a pre-defined string can be declared and used in a C program:

#include int main() {
char str[] = "Hello, World!";
printf("%s\n", str);
return 0;
}

In this example, the pre-defined string "Hello, World!" is assigned to a character array named str. The %s format specifier is used with printf to print the contents of the str array as a string. When the program is run, it outputs

Hello, World!

 

In C, there are several pre-defined functions that can be used to work with strings (arrays of characters). These functions are included in the string.h header file. Here are some commonly used pre-defined string functions in C:

strlen: Returns the length of a string (excluding the terminating null character)

#include 
#include 

int main() {
   char str[] = "Hello, World!";
   int length = strlen(str);
   printf("Length of string: %d\n", length);
   return 0;
}

 

strcpy: Copies the contents of one string to another

#include<stdio.h>
#include<string.h>

int main() {
   char source[] = "Hello, World!";
   char destination[20];
   strcpy(destination, source);
   printf("Copied string: %s\n", destination);
   return 0;
}

 

strcat: Concatenates two strings together

#include<stdio.h>
#include<string.h>

int main() {
   char str1[] = "Hello";
   char str2[] = ", World!";
   strcat(str1, str2);
   printf("Concatenated string: %s\n", str1);
   return 0;
}

 

strcmp: Compares two strings and returns a value based on their relative order

#include<stdio.h>
#include<string.> 

int main() {
   char str1[] = "abc";
   char str2[] = "def";
   int result = strcmp(str1, str2);
   printf("Result of comparison: %d\n", result);
   return 0;
}

These are just a few examples of the pre-defined string functions available in C. There are many more functions for manipulating strings that can be found in the string.h header file.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.