Strings in C

Strings in C with Examples

In this article, I am going to discuss the Strings in C with Examples. Please read our previous articles, where we discussed the Array in C. As part of this article, you will learn the following pointers in detail with examples.

  1. What are Strings in C?
  2. Why we need strings?
  3. Declaration and Initialization of String
  4. Memory representation of String
  5. Multiple Examples to understand string in C.
  6. What do u mean by formatted and unformatted function?
  7. Strings pre-defined functions with Examples
  8. Stringing Operator (#)
  9. Token Paste Operator (##)
  10. String related Interview questions in C
Strings in C:

Character array or group of characters or collection of characters are called strings. In implementation when we are manipulating multiple characters, then recommended going for strings. Within the ‘ ‘ any content is called character constant, within the “ “ any content is called string constant. Character constant always returns an integer value i.e. ASCII value of a character. String constant always returns the base address of a string. When we are working with a string constant, always ends with nul(‘\0’). The representation of the null character is nul(‘\0’) and the ASCII value is 0.

Syntax: char str[size];

Note: Null is a global constant value which is defined in <stdio.h>. Null is a macro which is having the replacement data as 0 or (void*)0.

Example: int x=NULL;
                 int *ptr=NULL;
nul(‘\0’) is an ASCII character data which is having ASCII value as 0.

Declaration of String:

C does not support string data type that’s why it allows us to represent the string as character arrays.

Syntax: char string_name[size];
Example: char book[10];

A null character (\0) is assigned to the string automatically when the compiler assigns a string to a character array. So, the size of the array becomes the maximum number of arrays plus 1.

Initialization of String:

We can initialize a String in different ways.

  1. char str[] = “Cprogramming”;
  2. char str[50] = “Cprogramming”;
  3. char str[] = {‘C’,’p’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,’\0′};
  4. char str[14] = {‘C’,’p’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,’\0′};
Memory representation of String:

Memory representation of String in C

Program:

#include<stdio.h>   
int main() 
{    
    // declare and initialize string 
    char str[] = "Strings";   
    // print string 
    printf("%s",str); 
    return 0; 
}

Output: Strings

Properties of Strings in C:
  1. In declaration of string, size must be unsigned integer constant whose value is greater than zero only.
  2. In the initialization of the string, specific characters are not initialized then remaining all elements are automatically initialized with nul(\0).
  3. In the initialization of the string, it is not possible to initialize more than the size of string elements.
  4. In the initialization of the string, if we are assigning numeric value, then according to ASCII value, corresponding data will be stored.
  5. In the initialization of the string, specifying the size is optional, in this case, how many characters are initialized that many variables are created.
  6. When we are working with strings, always recommended to initialize the data in double-quotes only.
  7. When we are working with a string constant, always it ends with ‘\0’ (null) character that’s why one extra byte memory is required but if we are working with character array then it doesn’t require one extra byte memory.
  8. When we are working with character operations recommended going for %c format specifier.
  9. When we are working with string operations recommended going for %s format specifier.
  10. When we are working with %s format specifier then we required to pass an address of a string, from given address up to null, entire content will print on console.
  11. When the null character has occurred in the middle of the string, then we are not able to print complete data because the null character indicates termination of string.
What do u mean by formatted and unformatted function?

The functions which will work with the help of format specifiers are called formatted function. A formatted function can be applied for any data type. For example: printf(), scanf(), fprintf(), fscanf(), sprint(), etc.

The functions which does not require any format specifier and need to be applied for specific data type only are called unformatted function. For example: puts(), gets(), fputs(), cgets(), getch(), etc.

puts():

It is a predefined unformatted function, which is declared in stdio.h. By using this function, we can print string data on the console. Puts() function required 1 argument of type char* and returns an integer value. When we are working with puts function, automatically it prints newline character after printing string data.

Syntax: int puts(char*str);

Program:
#include<stdio.h>
int main() 
{    
    char str[] = "Strings";  
    puts(str);
    printf("%s",str);
    return 0; 
}

Output:

What do u mean by formatted and unformatted functions in C?

Program:
#include<stdio.h>
#include<conio.h>
int main() 
{    
    char str[10];  
    printf("Enter a string: ");
    scanf("%s", str);
    printf("input string:%s", str);
    getch();
    return 0; 
}

Output:

What is a String in C Language?

By using scanf function, we can’t read the string data properly when we have multiple works because, in scanf function space, tab and newline characters are treated like separators so when the separator is present, it is replaced with \0 character. In sacnf function, when we are using %[^\n]s format specifier, then it indicates that read the string data up to newline character occurrence.

gets():

It is a predefined unformatted function that is declared in stdio.h. By using this function we can read the string data properly, even when we are having multiple words. gets() function requires one argument of type (char*) & returns (char*) only. In gets() function only a newline character is treated as a separator.

Syntax: char*gets(char*str);

Program:
#include<stdio.h>
#include<conio.h>
int main() 
{    
    char str[10];  
    printf("Enter a string: ");
    gets(str);
    printf("input string:%s", str);
    getch();
    return 0; 
}

Output:

Why we need strings in C?

Program:
#include<stdio.h>
#include<conio.h>
int main() 
{    
    char s1[10]="hello"; 
    char s2[10]="welcome";
    puts(s1);
    puts(s2);
    s2=s1;
    puts(s1);
    puts(s2);
    getch();
    return 0; 
}

Output:

Any kind of string manipulations, we can’t perform directly by using operators. In implementation when we required to perform any kind of string operations then recommended to go for any string handling functions or go for user-defined function logic.

Strings related pre-defined functions are declared in string.h:
  1. strcpy()
  2. strlen()
  3. strrev()
  4. strcat()
  5. strupr()
  6. strlwr()
  7. strcmp()
  8. stricmp()
  9. strstr()
strcpy():

By using this predefined function, we can copy a string to another string. It requires 2 arguments of type(char*) & return(char*) only. When we are working with strcpy() from given source address upto \0 entire content will be copied to destination string.

Syntax: char*strcpy(char*dest, const char*src);

Program: To understand strcpy() function in C
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main() 
{    
    char s1[10]="hello"; 
    char s2[10]="welcome";
    puts(s1);
    puts(s2);
    strcpy(s2,s1);
    puts(s1);
    puts(s2);
    return 0; 
}

Output:

Program: To understand strcpy() function in C

strlen():

By using this predefined function, we can find the length of the string. strlen() function requires 1 arguments of type (const char*) and returns an int type. When we are working with strlen() from the given address up to \0, the entire character count value will return.

Note: The length of the string means total no. of characters excluding \0 character. The size of the string means total no. of characters including \0 character.

Program: To understand strlen() function in C
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main() 
{    
    char str[]="welcome";
    int s,l;
    s=sizeof(str);
    l=strlen(str);
    printf("\nsize: %d",s);
    printf("\nlength: %d",l);
    getch();
    return 0; 
}

Output:

Program: To understand strlen() function in C

strrev():

By using this predefined function, we can reverse the string. strrev() requires 1 argument of type (char*) and returns (char*). When we are working with sterrev() from given address up to null entire string data will make reverse except for null character.

Syntax: char*strrev(char*str);

Program: To understand strrev() function in C
#include <stdio.h>
#include<conio.h> 
#include<string.h>
int main()
{
 char str[30]=”Welcome”;
 puts(str);
 strrev(str);	
 	printf("\n Reverse String is : %s", str);
 getch();
 return 0;	
}

Output:

Program: To understand strrev() function in C

strcat():

By using this predefined function, we can concatenate a string to another string. Concatenation means copying data from the end of the string i.e. appending process. strcat() requires 2 arguments of type (char*) and returns (char*) only.

Syntax: char*strcat (char*dest, const char*src);

When we are working with strcat() function, always appending will take place at the end of the destination only.

Program: To understand strcat() function in C
#include <stdio.h>
#include<conio.h> 
#include<string.h>
int main()
{
    	char s1[15]="hello";
 char s2[30]="HI";
 puts(s1);
 puts(s2);
 strcat(s2,s1);	
 	puts(s2);
 getch();
 return 0;	
}

Output:

Program: To understand strcat() function in C

strupr():

By using this predefined function, we can convert a string into upper case. strupr() function requires 1 argument of type (char*) and returns (char*). When we are working with strupr() function, from given address up to null all lower case characters are converted into uppercase.

Syntax: char*strupr(char*str);

Program: To understand strupr() function in C
int main() 
{ 
    char str[ ] = "Welcome to C programming language"; 
    //converting the given string into uppercase. 
    printf("%s\n", strupr (str)); 
    return  0; 
}

Output: Program: To understand strupr() function in C

strlwr():

By using this predefined function, we can convert a string into a lower case. strlwr() function requires 1 argument of type (char*) and returns (char*). When we are working with strlwr() function, from given address up to null all upper case characters are converted into lowercase.

Syntax: char*strlwr(char*str);

Program: To understand strlwr() function in C
#include<stdio.h> 
#include<string.h> 
int main() 
{ 
    char str[ ] = "GOOD MORNING"; 
    //converting the given string into uppercase. 
    printf("%s\n", strlwr (str)); 
    return  0; 
}

Output: good morning

strcmp():

By using this predefined function, we can compare strings. strcmp() requires 2 arguments of type (const char*) & returns an integer value. When we are working with strcmp(), then character by character comparison takes place until the first unpaired character set has occurred. When the first unpaired character set has occurred then it returns ASCII value difference. At the time of comparison if there is no difference, then it returns 0.

Program: To understand strcmp() function in C
#include <stdio.h>
#include<conio.h> 
#include<string.h>
int main()
{
    char s1[30]="hello";
 char s2[30]="hello";
 int d;
 puts(s1);
 puts(s2);
 d=strcmp(s1,s2);	
 	printf("ASCII Value difference: %d",d);
 getch();
 return 0;	
}

Output:

Program: To understand strcmp() function in C

stricmp()

By using this predefined function, we can compare the strings without any case i.e. uppercase and lowercase contents both are treated like same. When we are working with strcmp() function it works with the help of case i.e. uppercase and lowercase content both are different. stricmp() required 2 arguments of type (const char*) & returns an int value.

Syntax: int stricmp (const char*s1, const char*s2);

Program: To understand stricmp() function in C
#include <stdio.h>
#include<conio.h> 
#include<string.h>
int main()
{
    	char s1[30]="hello";
 char s2[30]="HELLO";
 int d;
 puts(s1);
 puts(s2);
 d=stricmp(s1,s2);	
 	printf("ASCII Value difference: %d",d);
 getch();
 return 0;	
}

Output:

Program: To understand stricmp() function in C

strstr()

By using this predefined function, we can find substring of a string. strstr() function requires 2 arguments of type const char* and returns char*.

Syntax: char*strstr (const char*str, const char*sub);

If the searching substring is available, then strstr() returns base address of substring else returns null.

Program: To understand strstr() function in C
#include <stdio.h>
#include<conio.h> 
#include<string.h>
int main()
{
    char s1[30]="HelloHiWelcome";
 char s2[30]="Hi";
 char*ptr;
 ptr=strstr(s1,s2);	
 	if (ptr)
 	{
 	    printf("String found\n"); 
                 printf("First occurrence of string '%s' in '%s' is '%s'", s2, s1, ptr);
 	}
 	else
 	{
 	    printf("\nsunstring not found");
 	}
 getch();
 return 0;	
}

Output:

Program: To understand strstr() function in C

Stringing Operator (#):

This operator is introduced in the NCC version. By using this operator, we can convert the text in the form of string i.e. replacement in ” “.

Program:

#include<stdio.h>
#define ABC(xy) printf(#xy "=%d",xy);
int main()
{
 int a,b;
 a=10;
 b=20;
 ABC(a+b);
 return 0;
}

Output: a+b=30

Token Paste Operator (##):

NCC programming language supports this operator. By using this operator, we can concatenate multiple tokens.

Program:

#include<stdio.h>
#define ABC(x,y) printf("%d",x##y);
void main()
{
 int var12=120;
 ABC(var,12);
 return 0;
}

Output: 120

In the next article, I am going to discuss String Exercises in C language. Here, in this article, I try to explain Strings in C. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article

Leave a Reply

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