logo codesdope

String in C


Maths and maths, codes and codes, but in the real world, we have to deal with words, sentences, etc. Is there anything in C which deals with these types of things? And the answer is yes, they are called strings.

We can think of strings as an array of characters, like 'Sam' is a string.

element 'S' 'a' 'm' '\0'
index 0 1 2 3

So, 'Sam' is an array of characters 'S', 'a', 'm' and '\0'

Look at the character at the 3rd index. It represents null character. ASCII value of '\0' is 0 and that of normal 0 is 48. It the represents termination (end) of a string.

We declare string as:-

char name[ ]= "Sam";

As you can see, the syntax of a string (char name[]) also tells us that it is an array of characters.

We always put a string in " " and a character in ' '.

We can also declare a string variable using characters as follows.

char name[ ]= {'S', 'a', 'm', '\0'};

Let's see two examples to print a string without and with for loop.

#include <stdio.h>
int main()
{
  char str[ ] = "Hello";
  printf("%s\n", str);
  return 0;
}
Output
Hello
Note that '%s' is used for string.

In the above example, we printed the whole string at once. Now we will see the same example but print individual characters using for loop.

#include <stdio.h>
int main()
{
  char str[ ] = "Hello";
  int i;
  for( i=0; i<6; i++)
  {
    printf("%c\n", str[i]);
  }
  return 0;
}
Output
H
e
l
l
o

In the first example, we printed string and for that we used %s with printf function. Whereas in the second example, we printed single character each time, so we used %c with the printf function.

Now let's see an example to input a string from user.

#include <stdio.h>
int main()
{
  char name[25];
  printf("Enter your name\n");
  scanf("%s", name);
  printf("Your name is %s\n", name);
  return 0;
}
Output
Enter your name
name
Your name is name

You must be wondering the reason for writing array size as 25 while declaring the name array. We did so because we do not know the length of the name that user will input. If in the above example we had given the array size as 2, then the string variable would not have taken the input because the size of the input is greater than the size of the array. So to be on the safe side, take the array size greater than the assumed input size.

Don't use '&' before the name of string while taking a string from user with scanf because in 'name[25]', 'name' is itself the pointer to 'name[25]'.
scanf takes only one word from user to a string variable. It terminates with any white space. Try to write something after space and it will take only the first word.

For example, if in the above example, we input Sam Brad as the name, then the output will only be Sam because scanf considers only one word and terminates after the first word.

How to take a multi word string


We can take input and give output of a string that consists of more than one word by using gets and puts, where gets is used to take input of a string from user and puts is used to display the string.

Consider the following example.

#include <stdio.h>
int main()
{
  char name[25];
  printf("Enter your name\n");
  gets(name);
  printf("Your name is ");
  puts(name);
  return 0;
}
Output
Enter your name
Sam Bard
You name is Sam Bard
If you are getting any warning for 'gets', just ignore it.
To print, you can also use printf instead of puts.
You can also use 'scanf ( "%[^\n]s", name );' for taking multi word string.

Pointers and String


Strings can also be declared using pointers. Let's consider an example.

#include <stdio.h>
int main()
{
  char name[ ]= "Sam";
  char *p;
  p = name; /* for string, only this declaration will store its base address */
  while( *p != '\0')
  {
    printf("%c", *p);
    p++;
  }
  return 0;
}
Output
Sam

In the above example, 'p' stores the address of name[0], therefore value of '*p' equals the value of name[0] i.e. 'S'. So in while loop, the first character gets printed and p++ increases the value of 'p' by 1 so that now p+1 points to name[1]. This continues until the pointer reaches the end of the string i.e., before '*p' becomes equals to '\0'.

Passing Strings to Functions


This is done in the same as we do with other arrays. The only difference is that this is an array of characters. That's it!

Let's see an example.

#include <stdio.h>
void display( char ch[])
{
  printf("String :");
  puts(ch); /* display string */
}
int main()
{
  char arr[30];
  printf("Enter string\n");
  gets(arr); /* input string from user */
  display(arr);
  return 0;
}
Output
Enter string
abcd
String :abcd

Predefined string functions


We can perform different kinds of string functions like joining of 2 strings, comparing one string with another or finding the length of the string. Let's have a look at the list of such functions.

Function Use
strlen calculates the length of string
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string

These functions are defined in "string.h" header file, so we need to include this header file also in our code by writing

#include <string.h>

We will see some examples of strlen, strcpy, strcat and strcmp as these are the most commonly used.

Make sure to check articles mentioned in the further reading of this chapter to see examples of each function available in the string.h library.

strlen(s1) calculates the length of string s1.

White space is also calculated in length of string.

#include <stdio.h>
#include <string.h>
int main()
{
  char name[ ]= "Hello";
  int len1, len2;
  len1 = strlen(name);
  len2 = strlen("Hello World");
  printf("length of %s = %d\n", name, len1);
  printf("length of %s = %d\n", "Hello World", len2);
  return 0;
}
Output
length of Hello = 5
length of Hello World = 11
strlen doesn't count '\0' while calculating the length of string.

strcpy(s1, s2) copies the second string s2 to the first string s1.

#include <string.h>
#include <stdio.h>
int main()
{
  char s2[ ]= "Hello";
  char s1[10];
  strcpy(s1, s2);
  printf("Source string = %s\n", s2);
  printf("Target string = %s\n", s1);
  return 0;
}
Output
Source string = Hello
Target string = Hello

strcat(s1, s2) concatenates(joins) the second string s2 to the first string s1.

#include <stdio.h>
#include <string.h>
int main()
{
  char s2[ ]= "World";
  char s1[20]= "Hello";
  strcat(s1, s2);
  printf("Source string = %s\n", s2);
  printf("Target string = %s\n", s1);
  return 0;
}
Output
Source string = World
Target string = HelloWorld

Note that in the above example, we gave array size to 's1' because we are adding the characters of another string to it. The array size given should be such that it is greater than or equal to the size of the string array after concatenation.

strcmp(s1, s2) compares two strings and finds out whether they are same or different. It compares the two strings character by character till there is a mismatch. If the two strings are identical, it returns a 0. If not, then it returns the difference between the ASCII values of the first non-matching pair of characters

#include <stdio.h>
#include <string.h>
int main()
{
  char s1[ ]= "Hello";
  char s2[ ]= "World";
  int i, j;
  i = strcmp(s1, "Hello");
  j = strcmp(s1, s2);
  printf("%d \n %d\n", i, j);
  return 0;
}
Output
0
-15

2D Array of Characters


Same as 2 D array of integers and other data types, we have 2 D array of characters also.

For example, we can write

char names[4][10] = {
                        "Andrew",
                        "Kary",
                        "Brown",
                        "Lawren"
            };

You are only as good as the chances you take.
- Al Pacino

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.