Strings in C

Strings in c is character type array and ends with the NULL character. %s placeholder is used in the printf() function to display string values.

String Declaration

char name[50];

Example

void main (void )
{

char *st1 = “abcd”;
char st2[] = “efgh”;
printf( “%s\n”, s1);
printf( “%s\n”, s2);

}

Example

void main(void){

char myname[] = {‘J’,’h’,’o’,’n’};

printf(“%s \n”,myname);

}

String input and output

The gets function relieves the string from standard input device while put S outputs the string to the standard output device.

The function gets accepts the name of the string as a parameter, and fills the string with characters that are input from the keyboard till newline character is encountered.

The puts function displays the contents stored in its parameter on the standard screen.

Syntax of the gets() function

gets (str_var);

Syntax of the puts() function

puts (str_var);

String input and output Example

# include < stdio.h >
void main ()
{

char myname [40];
printf (“Type your Name :”);
gets (myname);
printf (“Your name is :”);
puts(myname);

}

C String Functions

Function Description
strcpy(string1, string2) Copy string2 into string1
strcat(string1, string2) Concatenate string2 onto the end of string1
length = strlen(string) Get the length of a string
strcmp(string1, string2) Return 0 if string1 equals string2, otherwise nonzero
strchr(string1, chr); will find the first matching character in a string.

Leave a Reply

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