Strings in C With Syntax, C String Program with output

Strings in C:  Strings can be defined as the one-dimensional array of characters terminated by a null ('\0'). The difference between a character array and a string is the string is terminated with a special character ‘\0’.

Declaration of strings: Declaring a string is as simple as declaring a one-dimensional array.

Below is the basic syntax for declaring a string.


char str_n[size];

Explanation: In the above syntax str_n is any name given to the string variable and size is used to define the length of the string, that is the number of characters strings will store. 

Initializing a String: A string can be initialized in different ways see below:

1. char str[] = "Pappy";

2. char str[50] = "Pappy";

3. char str[] = {'P','a','p','p','y','\0'};

4. char str[14] = {'P','a','p','p','y','\0'};

Program:


#include <stdio.h>

int main () 
{
   char m[6] = {'P','a','p','p','y','\0'};
   printf("Entered:message  %s\n",m );
   return 0;
}

Output:

Entered message: Pappy

C String Function & Purpose


1) strcpy(x1, x2);  Copies string x2 into string x1.

2) strcat(x1, x2); Concatenates string s2 onto the end of string s1.

3) strlen(x1); Returns the length of string x1.

4) strcmp(x1, x2); Returns 0 if x1 and x2 are the same; less than 0 if x1<x2; greater than 0 if x1>x2.

5) strchr(x1, char); Returns a pointer to the first occurrence of character char in string x1

6) strstr(x1, x2);  Returns a pointer to the first occurrence of string x2 in string x1.

Program:

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

int main () {

   char s1[12] = "Tutorials";
   char s2[12] = "Webin";
   char s3[12];
   int  len ;

   /* copy s1 into s3 */
   strcpy(s3, s1);
   printf("strcpy( s3, s1) :  %s\n", s3 );

   /* concatenates s1 and s2 */
   strcat( s1, s2);
   printf("strcat( s1, s2):   %s\n", s1 );

   /* total lenghth of s1 after concatenation */
   len = strlen(s1);
   printf("strlen(s1) :  %d\n", len );

   return 0;
}

Output:
 
strcpy( str3, str1) :  Tutorials
strcat( str1, str2):   TutorialsWebin
strlen(str1) :  14


Share:

Ads

Search This Blog

  • ()
Powered by Blogger.

Strings in C With Syntax, C String Program with output

Strings in C :  Strings can be defined as the one-dimensional array of characters terminated by a null ('\0'). The difference betwee...