Strings in C

Strings in C

Strings in C

  • 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];
  • In C language we can use #include<string.h> for different string manipulation operations.
  • 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'};

Representation of Strings

String Representation

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 statment.
  • String b is getting input from gets statemnet

Program to demonstrate getting Input.

#include <stdio.h>
int main()
{
char a[20];
char b[30];
scanf("%s",a);
gets(b);
}
  • 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

Program to demonstrate printing String.

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