INTRODUCTION TO STRING

The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

  1. By char array
  2. By string literal

Let's see the example of declaring string by char array in C language.

  1. char ch[10]={'j''a''v''a''t''p''o''i''n''t''\0'};  

As we know, array index starts from 0, so it will be represented as in the figure given below.

C Strings

While declaring string, size is not mandatory. So we can write the above code as given below:

  1. char ch[]={'j''a''v''a''t''p''o''i''n''t''\0'};  

We can also define the string by the string literal in C language. For example:

  1. char ch[]="javatpoint";  

In such case, '\0' will be appended at the end of the string by the compiler.

Difference between char array and string literal

There are two main differences between char array and literal.

  • We need to add the null character '\0' at the end of the array by our self whereas, it is appended internally by the compiler in the case of the character array.
  • The string literal cannot be reassigned to another set of characters whereas, we can reassign the characters of the array.
Sr.No.Function & Purpose
1

strcpy(s1, s2);

Copies string s2 into string s1.

2

strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3

strlen(s1);

Returns the length of string s1.

4

strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5

strchr(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.


Popular posts from this blog

DATA STRUCTURES-II

DATA STRUCTURES FOR BCA

DATA STRUCTURES FOR B.TECH