String in C Programming Language
In this post, We will learn about string in C programming language.
In this post, We will learn about string in C programming language.
Introduction
A string in C is merely an array of characters. The length of a string is determined by a terminating null character: '\0'. So, a string with the contents, say, "abc" has four characters: 'a', 'b', 'c', and the terminating null character.Initialize String in C
Suppose you want to store Rozgardesh in String str you can do using one of below way
1. char str[] = "RozgarDesh";
2. char str[50] = "RozgarDesh";
3. char str[] = {'R','o','z','g','a','r','d','e','s','h','\0'};
4. char str[11] = {'R','o','z','g','a','r','d','e','s','h','\0'};
Display String
Here is an example to display the value of a string variable on the terminal.
#include<stdio.h>
int main()
{
// declare and initialize string
char str[] = "Rozgardesh";
// print string
printf("%s",str);
return 0;
}
String as User Input
Here is an example to take a string input from the user // C program to read strings
#include<stdio.h>
int main()
{
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
}
The more commonly-used string functions
The nine most commonly used functions in the string library are:- strcat - concatenate two strings
- strchr - string scanning operation
- strcmp - compare two strings
- strcpy - copy a string
- strlen - get string length
- strncat - concatenate one string with part of another
- strncmp - compare parts of two strings
- strncpy - copy part of a string
- strrchr - string scanning operation
All these functions come under <string.h> library. So in order to use these function, you have to include <string.h> header file in your source code. We will discuss examples of these function in another post.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Comments
Post a Comment