top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

String Handling in C

+1 vote
601 views

There is nothing called string in C, an string in C is a array of chars which is terminated at null ('\0') character like

char name[10] = "QueryHome";

String Declaration Syntax

char variable_name [string_size] ;

String Initialization

a. char name [] = {'Q','u','e','r','y','H','o','m','e','\0'};
b. char name[10] = "QueryHome";
c. char *name = "QueryHome";

Input a String

In C we can input a string using scanf with %s option or gets function.

scanf("%s", variable); // %s in scanf is white character terminated 
gets(variable); // terminated at the newline 

Output a String

In C we can output a string using printf with %s option or puts function.

printf("%s", variable/string); 
puts(string/variable);

String Library Function

Header File: string.h or strings.h

strcpy: copy a string and is used like this: strcpy(destination, source).

strcmp: compare two strings and can be used like this: strcmp(str1, str2).
If the first string is greater than the second string a number greater than null is returned.
If the first string is less than the second string a number less than null is returned.
If the first and the second string are equal a null is returned.

strcat: concatenates a string onto the end of the other string which can be used like this strcat(str1, str2) and returns str1str2

strlen: returns the length of the string and used like this strlen(str);

strstr: Finds the first occurrence of a string (str2 into str1) into other and return the pointer of it else returns null and is used as strstr(str1, str2)

atoi: returns the integer value of a string and used as atoi(String);

posted Aug 16, 2014 by Salil Agrawal

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...