Tuesday, 26 November 2013

String In C

The string in C programming language is a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
 C Programming
C Programming


The declaration and initialization for creating a a word "World".To determine the end of the string ,there is a symbol ('\0') at the end of the array which means null character.

char greeting[6] = {'W', 'o', 'r', 'l', 'd', '\0'};
The declaration of a string in C Programming language is:
 char a[] = "Hello";
 The memory presentation of above defined string in C Programming language is:

String Presentation in C:

 You not need to  place the null character at the end of a string by yourself. The C compiler automatically places the '\0' at the end of the string when it initializes the array.

#include <stdio.h>

int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   printf("Greeting message: %s\n", greeting );

   return 0;
}
Output:
Greeting message: Hello
C Provide a wide range of functions that manipulate null-terminated strings:

S.N.   Function & Purpose
1strcpy(s1, s2);      Copies string s2 into string s1.
2strcat(s1, s2);       Concatenates string s2 onto the end of string s1.
3strlen(s1);             Returns the length of string s1.
4strcmp(s1, s2);     Returns 0 if s1 and s2 are the same; less than 0 if                                                   s1<s2; greater than 0 if s1>s2.
5strchr(s1, ch);       Returns a pointer to the first occurrence of character                                             ch in string s1.
6 strstr(s1, s2);       Returns a pointer to the first occurrence of string s2                                               in string s1.

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

int main ()
{
   char str1[12] = "Hello";
   char str2[12] = "World";
   char str3[12];
   int  len ;

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

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

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

   return 0;
}
OutPut:

strcpy( str3, str1) :  Hello
strcat( str1, str2):   HelloWorld
strlen(str1) :  10

C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments


0 comments:

Post a Comment