Strings in C programming

Strings in C programming

Strings in C are defined as the one-dimensional array of characters end by a null. It is used to handle words and each character of array occupies one byte of memory, and the last character always is 0.

Create a string in c programming

There are many techniques to declare a c-string

Syntax

char str_name[size];

 

Initializing a Strings in C programming

A string is initialized in different ways. Below is an example to declare a string with the name as ‘str’ and initialize it with “abcde”.

C strings examples

char str[] = "abcde";

char str[50] = "abcde";

char str[] = {'a','b','c','d','e','\0'};

char str[5] = {'a','b','c','d','e','\0'};

Access character of a String

A character of a string is accessed with an index number. Index number starts with 0 in the forwarding direction. 

 

Program for access character of the string in C programming

#include <stdio.h>

int main () {

   char str[6] = {'s', 't', 'u', 'd', 'y', '\0'};
   printf("string: %s\n", str );
   return 0;
}

Output

String: study

 

The following example describes how to access the character of a string using its index number.

 

Access characters of the string in c programming

#include <stdio.h>
 
int main (){
  char str[] = "study";

  printf("%c\n", str[1]);
  printf("%c\n", str[4]);
  return 0;
}

Output

t
y

 

String manipulation in C

Function Purpose
strcpy(s1, s2); strycpy is used to copies string s2 into string s1.
strcat(s1, s2); strcat is used to concatenates string s2 onto the end of string s1.
strlen(s1); strlen is used to returns the length of string s1.
strcmp(s1, s2); strcmp is uesd to returns 0 if s1 and s2 are the same, less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch); strchr is used to returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2); strstr is used to returns a pointer to the first occurrence of string s2 in string s1.

 

Program for string manipulating in C

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

int main () {

   char str1[12] = "Study";
   char str2[12] = "Expert";
   char str3[12];
   int  len ;

   /* copy */
   strcpy(str3, str1);
   printf("strcpy( str3, str1) :  %s\n", str3 );

   /* concatenates */
   strcat( str1, str2);
   printf("strcat( str1, str2):   %s\n", str1 );

  
   len = strlen(str1);
   printf("strlen(str1) :  %d\n", len );

   return 0;
}

Output

strcpy( str3, str1) :  Study
strcat( str1, str2):   StudyExpert
strlen(str1) :  10

 

Also read, C-Operators

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *