Strings in C

Strings in C

Strings

Strings are one dimensional character array. Strings always terminate by null character “\0” having the ASCII value zero as well. Strings data types also follows contagious memory allocation.  Basic Syntax of String Declaration is Char String_Name[String Size]; Operations include stelen, strcpy, strcmp, strcat etc.

Declaration of Strings

  • In method 1 we also set String size along with string name and char keyword for declaration of string.
  • In method 2 we do not set String Size along with string Name and char keyword.
  • It will automatically take the size of the of string.
Method 1
char String_Name [String_Size];
Method 2
char String_Name [];

Initialization of Strings

Method 1 : Type 1
char a [11] = "prepinsta";
Method 1 : Type 2
char a [11] = {'p','r','e','p','i','n','s','t','a','\0'};
Method 2 : Type 1
char a [] = "prepinsta";
Method 2 : Type 2
char a [] = {'p','r','e','p','i','n','s','t','a','\0'};
string

Scanning and Printing of String.

  • Scanning can be done via 2 methods.
  • first is the use of scanf statement.
  • second is the use of gets statement.
  • In the following Program basically there are two strings  and  b.
  • String a is getting input from scanf statement.
  • String b is getting input from gets statement.

Program to demonstrate getting Input.

#include<stdio.h>
int main()
{
     char a[20];
     char b[30];
     scanf("%s",a);
     gets(b);
}

Program to demonstrate printing String.

  • Printing can be done via 2 methods.
  • first is the use of printf statement.
  • second is the use of puts statement.
  • In the following Program basically there are two strings  and  b.
  • String a is getting input from scanf statement.
  • String b is getting input from gets statement.
  • String a getting printed via printf Statement.
  • While String b is getting printed via puts statement
#include<stdio.h> 
int main()
{
     char a[20];
     char b[30];
     scanf("%s",a);
     gets(b);
     printf("%s",a);
     puts(b);
}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription