Skip to content

Strings In C

What are strings?

A string is a one dimensional array of characters that ends with the null character (‘\0’). This array or string is used to control text be it words or sentences. Every character of the array holds one byte of memory, and the last character must terminate with 0. It is crucial to put a termination character (‘\0’) as it is the sole way to identify the end of the string. When a string is set out such as char s[20], it initializes the s[20] character in the memory with a null character (‘\0’).

A string in c programming is declared in two ways:

  1. By char array.
  2. By string literal.

Here is an example of declaring a string in c programming by char array:

We’re well aware of the fact that an array index commences with the null character as represented above. The size is not a mandatory factor when a string is declared. So, the above code can be written as:

Char ch[]={‘H’, ‘e’, ‘l’ , ‘l’, ‘o’, ‘\0’};

Strings in c can also be defined as by the string literal in c programming. For example:

Char ch[]=”Hello”;

In this example,the character ( ‘\0’) is attached by the compiler at the end of the string.

Contrast between a character array and string literal:

The primary distinctions between a character array and literal in c are:

  • At the bottom of the array, we should add the character \0 to the compiler whilst an array of characters is attached internally to it.
  • The literal string cannot be reallocated to a different collection of characters whereas the characters of the array can be allocated.

Example of strings in c.

Let’s see an example of a string being specified and printed. The ‘%s’ is used as a c- programming string format specifier.

code:

Output:

Traversing string

One of the main aspects to be covered in the C programming language is traversal of strings. We may need to manipulate a large segment of text, which can be accomplished by traversing the text. Traversal of the string and an integer array are somewhat different from each other.To traverse an integer array, the length of the array must be known, but in the case of string, we can use the null character to identify the end of the string and terminate the loop.

We can traverse a string in two ways:

  • Using the length of the string.
  • Using the null character.

Let’s get into each one in detail:

Using the length of the string:

The following is the code example of the number of vowels in a string.

code:

#include<stdio.h>

void main ()

{

char s[14] = “codewithgeeks”;

int i = 0;

int count = 0;

while(i<14)

{

if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘o’ || s[i] == ‘u’)

{

count ++;

}

i++;

}

printf(“The number of vowels is %d”,count);

}

Output:

The number of vowels is 5.

Using the null character:

Here is the same example done with this alternate method:

code:

#include<stdio.h>

void main ()

{

char s[14] = “Codewithgeeks”;

int i = 0;

int count = 0;

while(s[i] != NULL)

{

if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘o’ || s[i] == ‘u’)

{

count ++;

}

i++;

}

printf(“The number of vowels is %d”,count);

}

Output:

The number of vowels is 5.

Accepting the string as input

We’ve been using the scanf function till now to enable the user to give their own input. However, we can utilise this in case of string but under different circumstances. Consider the code given below, which saves the string whenever a space is encountered.

code:

#include <stdio.h>

void main()

{

char s[20];

printf(“Enter the string?”);

scanf(“%s”,s);

printf(“You entered %s”,s);

}

Output:

Enter the string?codewithgeeks

You entered codewithgeeks

We should also take into consideration that in the above code, to use the address of(&) operator in the scanf function is needed to save a string since the string is an array of characters and the name of array, i.e., s, specifies the base address of string (character array), so we do not need to use & with it.

Important points:

There are a few things to keep in mind while using scanf to enter a string.

  • Alternatively gets() which is an inbuilt function is used instead of using scanf defined in a header file string.h. The gets() can receive only one string at a time.
  • The compiler does not verify the limits of a character array. Consequently, there is a chance that the length of a string exceeds the dimension of the character array, which will always overrule some critical data.

Pointer with strings

We have learnt to use pointers along with arrays, functions and primitive data types till now. Pointers, on the other hand, can be used to point to the strings. There are several benefits of utilising pointers to point strings. Consider the following example of using a pointer to access a string.

Code:

#include <stdio.h>

void main ()

{

char s[14] = “codewithgeeks”;

char *p = s; // pointer p is pointing to string s.

printf(“%s”,p); // the string codewithgeeks is printed if we print p.

}

Output:

Codewithgeeks

As we’re very well aware that a string in the c programming language is an array of a number of characters, so you can use pointers in the same manner as arrays. In the example shown above, p is used to declare a reference to a character array. P and s have the same effect since s is the string’s base address and is handled as a pointer internally. We must utilise pointers to store strings for this reason. In the above example, we used pointers to replicate the contents of two strings.

code:

#include <stdio.h>

void main ()

{

char *p = “hello codewithgeeks”;

printf(“Before assigning: %s\n”,p);

p = “hello”;

printf(“After assigning: %s\n”,p);

}

Output:

Before assigning: hello codewithgeeks

After assigning: hello

String Functions

Strings in c provide an extensive range of functions for manipulating null terminated strings.

Despite its nonvariable type categorization, the C programming library does not scrimp on string manipulation methods. Using some of the numerous string functions, you can do almost whatever you want with a string. And if those functions are insufficient, you may create your own. Here are some functions in c that are used to manipulate strings:

  1. strcpy(s1, s2);

Copies a string s2 into s1.

  1. strcat(s1, s2);

CAppends string s2 to the end of string s1.

  1. strlen(s1);

Returns length of string s1.

  1. strchr(s1, ch);

A pointer is returned to the first occurrence of character ch in string s1.

  1. strcmp(s1, s2);

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

  1. strstr(s1,s2);

The first occurrence of string s2 in string s1 is returned as a pointer.

Note: To use string functions, the string.h header file must be used.

Code:

#include<stdlib.h>

#include <stdio.h>

int main()

{

char str1[]= “Hello”;

char str2[]=”Hello”;

if(!strcmp(str1, str2))

{

printf(“The strings are same”);

}

else

{

printf(“The strings are different”);

}

}

nv-author-image

Vaibhav Kapoor

A professional web entrepreneur, WordPress developer and digital marketing strategist with more than 4 years of experience in building a business from scratch. Knowledgeable about SEO, blogging, internet marketing, social media and website development.

Leave a Reply

Your email address will not be published. Required fields are marked *

[wpfepp_submission_form form="1"]