String and Character Array

A string is a sequence of characters terminated with a null(‘\0’) character. C does not have a string data types. Basically, string is a one-dimensional array of characters.

Please refer to the article on array in C before moving further down and also refer to the below topics:

For example, the string “techaccess” contains 11 characters including a null character added at the end by default by the compiler.

char str[] = “techaccess”;

index012345678910
strtechaccess‘\0’
Address0x200x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x210

A character array is a collection of variables that are of type “char”. It is a sequence of characters that are stored in consecutive memory locations.

Declare a character array:

char arr[10];

This is an array that holds character values and the maximum value it can store is 10.

We must specify the size while declaring any type of array.

Declaration and initialization of array:

/* Declaration and initialization but compiler appends the string with null character*/
char str[10] = "techaccess";

/* Declaration and initialization but explicitly needs to append with null character*/
char str[11] = {'t', 'e', 'c', 'h', 'a', 'c', 'c', 'e', 's', 's', '\0'};

/* Size is not mentioned */
char str[] = {'t',  'e',  'c',  'h',  'a',  'c', 'c', 'e', 's', 's',  '\0'};

/* Elements are less than the size, the rest may contain garbage values */
char str[6] = {'a', 'd', 'i', 't', '\0'};

/* Initializing all the elements with NULL */
char str[6] = {'\0'};

/*Illegal as more elements than size of array */
char str[4] = "techaccess";
char str[4] = {'t', 'e', 'c', 'h', 'a', 'c', '\0'};

Access the string or the character array:

This can also be accessed with their subscript or their index

#include <stdio.h>

int main()
{
    char arr[] = {'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e','\0'};
    printf("\n Address of 1st value is :%p ", arr);
    printf("\n Address of 2nd value is :%p ", arr + 1 );
    printf("\n Address of 3rd value is :%p ", arr + 2);
    
    printf("\n value of 1st element is :%c", arr[0]);
    printf("\n value of 2nd element is :%c ", arr[1]);
    printf("\n value of 3rd element is :%c ", arr[2]);
    printf("\n value of 4th element is :%c ", *(arr + 3));
    
    return 0;
}

OUTPUT:

Address of 1st value is :0x7fff77b1776f
Address of 2nd value is :0x7fff77b17770
Address of 3rd value is :0x7fff77b17771
value of 1st element is :l
value of 2nd element is :a 
value of 3rd element is :n 
value of 4th element is :g 

Note:

  • Whenever we are declaring and initializing a char array value separated by comma(,), it should always end with ‘\0’.(NULL-terminated).
    char arr[] = {‘l’, ‘a’, ‘n’, ‘g’, ‘u’, ‘a’, ‘g’, ‘e’,’\0′};
  • We use %c to fetch each value with their index.
  • In the case of the character array, each value is stored at a difference of 1 byte as the size of the char is 1 byte.

String input and output:

  • %s format specifier to read a string input from the terminal.
  • But scanf() function, terminates its input on the first white space it encounters.
  • The fgets() function can also be used to get a string with whitespace and fputs() for output.

Example:

scanf() and printf():

#include <stdio.h>

int main()
{
 char str[10];
 printf ("\n Enter the string\n");
 scanf("%s", &str);
 printf("\n The string is %s\n", str);
 return 0;
}

Output:

Enter the string
techaccess

 The string is techaccess

fgets() and fputs():

#include <stdio.h>

int main()
{
 char str[15];
 FILE *ptr;
 ptr= fopen("a.txt", "w+");
 printf("\n Enter the string\n");
 fgets(str, 15, stdin);
 fputs(str,ptr);
 return 0;
}

Output:

Enter the string
  tech access
A new file will be created and "tec access" will be written into it.

String handling function:

C language comes with many built-in functions for the manipulation of string under string.h header file.

The most commonly used functions related to string are as follows:

FunctionDefinition
strlen()It is used to get the length of the string
strcmp()It is used to compare the two string
strcat()It concatenates (combines) the two strings
strrev()It reverses the given string
strcpy()It copies the string from source to destination

Length of the string:
The length of the string can be found by using a function named strlen().

Compare the two strings:
This can be done with the function named strcmp(). If the strings happen to be the same, it returns 0 else non-zero.  It returns to the ASCII difference between the first unmatched character of two strings.

Syntax:

int ret = strcmp (str1, str2);

Combining the two strings:
The two strings can be combined with a function named strcat().

str1TECH
str2ACCESS
concat_strTECHACCESS

Reverse the string:
The string can be reversed by using the function named strrev().

strTECH\0
rev_str()HCET\0

Copying the string:
This can be done by using a function named strcpy().

Syntax:

strcpy(dest_str1, src_str2);

Examples:

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

int main ()
{
   char str1[] = "techaccess";
   char str2[] = "info";
   printf ("\n The length of the string:%s is: %d\n", str1, strlen(str1));
   int ret = strcmp (str1, str2);
   if (ret)
      printf("\n The two strings(%s and %s) are not equal\n", str1, str2);
   else
      printf("\n The two strings(%s and %s) are equal\n", str1, str2);

   printf("\n The concateneted string is: %s\n", strcat(str1, str2));
   printf("\n The reverse of %s is: %s\n", str1, strrev(str1));

   char str3[strlen(str2)];
   strcpy(str3, str2);
   printf("\n Copied string is: %s\n", str3);
   
   return 0;
}

Output:

The length of the string:techaccess is: 10

The two strings(techaccess and info) are not equal

The concateneted string is: techaccessinfo
The reverse of techaccess is: sseccahcet

Copied string is: info


Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: