0% found this document useful (0 votes)
189 views

C String

C strings are arrays of characters terminated by a null character. They do not have their own datatype in C and are instead declared as character arrays. Common string functions in C include strcat() to concatenate strings, strcpy() to copy strings, strlen() to return the length of a string, and strcmp() to compare two strings.

Uploaded by

Shivam Saxena
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
189 views

C String

C strings are arrays of characters terminated by a null character. They do not have their own datatype in C and are instead declared as character arrays. Common string functions in C include strcat() to concatenate strings, strcpy() to copy strings, strlen() to return the length of a string, and strcmp() to compare two strings.

Uploaded by

Shivam Saxena
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

C – String

 C Strings are nothing but array of characters ended with null character (‘\0’).
 This null character indicates the end of the string.
 Strings are always enclosed by double quotes. Whereas, character is
enclosed by single quotes in C.

string and Character array

string is a sequence of characters that is treated as a single data item and


terminated by null character '\0'. Remember that C language does not support
strings as a data type. A string is actually one-dimensional array of characters in C
language. These are often used to create meaningful and readable programs.

Declare and initialize a String

A string is a simple array with char as a data type. 'C' language does not directly support string as
a data type. Hence, to display a string in 'C', you need to make use of a character array.

The general syntax for declaring a variable as a string is as follows,

char string_variable_name [array_size];

The classic string declaration can be done as follow:

char string_name[string_length] = "string";

The size of an array must be defined while declaring a string variable because it used to calculate
how many characters are going to be stored inside the string variable. Some valid examples of
string declaration are as follows,

char first_name[15]; //declaration of a string variable


char last_name[15];

The above example represents string variables with an array size of 15. This means that the given
character array is capable of holding 15 characters at most. The indexing of array begins from 0
hence it will store characters from a 0-14 position. The C compiler automatically adds a
NULL character '\0' to the character array created.

Let's study the initialization of a string variable. Following example demonstrates the
initialization of a string variable,

char first_name[15] = "ANTHONY";


char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character
'\0' is required at end in this declaration
char string1 [6] = "hello";/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */
char string2 [ ] = "world"; /* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6
*/
char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of
characters ,Size 6*/

In string3, the NULL character must be added explicitly, and the characters are enclosed in
single quotation marks.

'C' also allows us to initialize a string variable without defining the size of the character array. It
can be done in the following way,

char first_name[ ] = "NATHAN";

The name of a string acts as a pointer because it is basically an array.

 Some examples of illegal initialization of character array are,


 char ch[3] = "hell"; // Illegal

 char str[4];
 str = "hell"; // Illegal

String Input and Output

Input function scanf() can be used with %s format specifier to read a string input
from the terminal. But there is one problem with scanf() function, it terminates its
input on first white space it encounters. Therefore if you try to read an input string
"Hello World" using scanf() function, it will only read Hello and terminate after
encountering blank space after hello.

White space includes blanks, tabs, new lines, carriage return and form feed.

However, C supports a format specification known as the edit set conversion


code that can be used to read a line containing a variety of characters, including
white spaces. Example;

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
clrscr();
printf("Enter a string");
scanf("%[^\n]",&str); //scanning the whole string,including the white spaces
printf("%s",str);
getch();
}
Method-2 to read and writing character string with white spaces from terminal is
gets() function and puts() function respevtively.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char text[20];
gets(text);
puts(text);
getch();

method3: getchar() & putchar() functions

The getchar() function reads a character from the terminal and returns it as an
integer. This function reads only single character at a time. You can use this
method in the loop in case you want to read more than one characters. The
putchar() function prints the character passed to it on the screen and returns the
same character. This function puts only single character at a time. In case you want
to display more than one characters, use putchar() method in the loop.

Example showing use of getchar() & putchar() functions to read and write single
charater;
#include <stdio.h>
#include <conio.h>
void main( )
{
int c;
printf("Enter a character");
c=getchar();
putchar(c);
getch();
}

When you will compile the above code,it will ask you to enter a value. When you
will enter the value, it will display the value you have entered.

getchar() Example : Accepting String (Use One of the Loop)


#include<stdio.h>
#include<conio.h>
void main()
{
int i = 0;
char name[20];
printf("\nEnter the Name : ");
while((name[i] = getchar())!='\n')
i++ ;
name[i]=’\0’;
getch();
}

Explanation of the above Program :


while((name[i] = getchar())!='\n')
i++ ;

above while loop will accept the one character at a time and check it with newline
character. Whenever user enters newline character then control comes out of the
loop. ’\0’ is last element of string to be entered by user.

Putchar function : Displaying String in C Programming

#include< stdio.h>
#include< conio.h>

void main()
{
char string[] = "This is an example string\n";
int i=0;
clrscr();

while(string[i]!='\0')
{
putchar(string[i]);
i++;
}
getch();
}

C String functions:

 String.h header file supports all the string functions in C language. All the
string functions are given below.

String
Description
functions
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns
strcmp ( )
>0 if str1 > str2
Same as strcmp() function. But, this function negotiates case.  “A”
strcmpi ( )
and “a” are treated as same.
strchr ( ) Returns pointer to first occurrence of char in str1
strrchr ( ) last occurrence of given character in a string is found
strstr ( ) Returns pointer to first occurrence of str2 in str1
strrstr ( ) Returns pointer to last occurrence of str2 in str1
strdup ( ) Duplicates the string
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase
strrev ( ) Reverses the given string
strset ( ) Sets all character in a string to given character
strnset ( ) It sets the portion of characters in a string to given character
strtok ( ) Tokenizing given string using delimiter

C – strcat() function

 strcat( ) function in C language concatenates two given strings. It


concatenates source string at the end of destination string. 
 Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.

 As you know, each string in C is ended up with null character (‘\0’).


 In strcat( ) operation, null character of destination string is overwritten by
source string’s first character and null character is added at the end of new
destination string which is created after strcat( ) operation.

C – strcpy() function

 strcpy( ) function copies contents of one string into another string.


 Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.

 If destination string length is less than source string, entire source string
value won’t be copied into destination string.
 For example, consider destination string length is 20 and source string length
is 30. Then, only 20 characters from source string will be copied into
destination string and remaining 10 characters won’t be copied and will be
truncated.

C – strlen() function
 strlen( ) function in C gives the length of the given string.  strlen( ) function
counts the number of characters in a given string and returns the integer
value.

 It stops counting the character when null character is found. Because, null
character indicates the end of the string in C.

C – strcmp() function

 strcmp( ) function in C compares two given strings and returns zero if they
are same.

 If length of string1 < string2, it returns < 0 value. If length of string1 >
string2, it returns > 0 value.
 strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different
characters.

C – strcmpi() function

 strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function


is not case sensitive. i.e, “A” and “a” are treated as same characters. Where
as, strcmp() function treats “A” and “a” as different characters.
 strcmpi() function is non standard function which may not available in
standard library in C.
 Both functions compare two given strings and returns zero if they are same.
 If length of string1 < string2, it returns < 0 value. If length of string1 >
string2, it returns > 0 value.

C – strchr() function

strchr( ) function returns pointer to the first occurrence of the character in a given
string.

Example program for strchr() function in C:In this program, strchr( ) function
is used to locate first occurrence of the character ‘i’ in the string “This is a
string for testing”. Character ‘i’ is located at position 3 and pointer is
returned at first occurrence of the character ‘i’.

#include <stdio.h>

#include <string.h>
int main ()

  char string[55] ="This is a string for testing";

  char *p;

  p = strchr (string,'i');

printf ("Character i is found at position %d\n",p-string+1);

  printf ("First occurrence of character \"i\" in \"%s\" is" \

           " \"%s\"",string, p);

  return 0;

Output:
Character i is found at position 3
First occurrence of character “i” in “This is a string for testing” is “is is a string for
testing”

Note: If you want to find each occurrence of a character in a given string, you can
use below C program.

#include <stdio.h>

#include <string.h>

int main ()

  char string[55] ="This is a string for testing";

  char *p;

  int k = 1;

  p = strchr (string,'i');

  while (p!=NULL)

  {
    printf ("Character i found at position %d\n",p-string+1);

    printf ("Occurrence of character \"i\" : %d \n",k);

    printf ("Occurrence of character \"i\" in \"%s\" is \"%s" \

            "\"\n",string, p);

    p=strchr(p+1,'i');

    k++;

  }

  return 0;

Output:
Character i is found at position 3
Occurrence of character “i” : 1
Occurrence of character “i” in “This is a string for testing” is “is is a string for
testing”
Character i is found at position 6
Occurrence of character “i” : 2
Occurrence of character “i” in “This is a string for testing” is “is a string for testing”
Character i is found at position 14
Occurrence of character “i” : 3
Occurrence of character “i” in “This is a string for testing” is “ing for testing”
Character i is found at position 26
Occurrence of character “i” : 4
Occurrence of character “i” in “This is a string for testing” is “ing”

C – strrchr() function

strrchr( ) function in C returns pointer to the last occurrence of the character in a


given string.

Example program for strrchr() function in C:

In this program, strrchr( ) function is used to locate last occurrence of the character
‘i’ in the string ”This is a string for testing”. Last occurrence of character ‘i’ is
located at position 26 and pointer is returned at last occurrence of the character ‘i’.

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

int main ()

  char string[55] ="This is a string for testing";

  char *p;

  p = strrchr (string,'i');

  printf ("Character i is found at position %d\n",p-string+1);

  printf ("Last occurrence of character \"i\" in \"%s\" is" \

           " \"%s\"",string, p);

  return 0;

Output:
Character i is found at position 26
Last occurrence of character “i” in “This is a string for testing” is “ing”

C – strstr() function

strstr( ) function returns pointer to the first occurrence of the string in a given
string.

Example program for strstr() function in C:

In this program, strstr( ) function is used to locate first occurrence of the string
“test” in the string ”This is a test string for testing”. Pointer is returned at
first occurrence of the string “test”.

#include <stdio.h>

#include <string.h>

int main ()

{
  char string[55] ="This is a test string for testing";

  char *p;

  p = strstr (string,"test");

  if(p)

  {

    printf("string found\n" );

    printf ("First occurrence of string \"test\" in \"%s\" is"\

           " \"%s\"",string, p);

  }

  else printf("string not found\n" );

   return 0;

Output:
string found
First occurrence of string “test” in “This is a test string for testing” is “test string for
testing”

C – strrstr() function

 strrstr( ) function returns pointer to the last occurrence of the string in a


given string. strrstr( ) function is non standard function which may not
available in standard library in C.

Example program for strrstr() function in C:

In this program, strrstr( ) function is used to locate last occurrence of the string
“test” in the string ”This is a test string for testing”. Pointer is returned at last
occurrence of the string “test”.

1 #include <stdio.h>
2 #include <string.h>
3 int main ()
4 {
5   char string[55] ="This is a test string for testing";
6   char *p;
7   p = strrstr (string,"test");
8   if(p)
9   {
10     printf("string found\n" );
11     printf ("Last occurrence of string \"test\" in \"%s\" is"\
12            " \"%s\"",string, p);
13   }
14   else printf("string not found\n" );
15    return 0;
16 }

Output:

string found
Last occurrence of string “test” in “This is a test string for testing” is “testing”

C – strlwr() function

 strlwr( ) function converts a given string into lowercase. strlwr( ) function is


non standard function which may not available in standard library in C.

Example program for strlwr() function in C:

In this program, string “MODIFY This String To LOwer” is converted into lower case
using strlwr( ) function and result is displayed as “modify this string to lower”.

#include<stdio.h>
#include<string.h>
int main()
{
    char str[ ] = "MODIFY This String To LOwer";
    printf("%s\n",strlwr (str));
    return  0;
}

Output:

modify this string to lower

C – strupr() function

 strupr( ) function converts a given string into uppercase. strupr( ) function is


non standard function which may not available in standard library in C.
Example program for strupr() function in C:

In this program, string “Modify This String To Upper” is converted into uppercase


using strupr( ) function and result is displayed as “MODIFY THIS STRING TO
UPPER”.

#include<stdio.h>
#include<string.h>
 int main()
{
    char str[ ] = "Modify This String To Upper";
    printf("%s\n",strupr(str));
    return  0;
}

Output:

MODIFY THIS STRING TO UPPER

C – strrev() function

 trrev( ) function reverses a given string in C language.


 strrev( ) function is non standard function which may not available in
standard library in C.

Example program for strrev() function in C:

In below program, string “Hello” is reversed using strrev( ) function and output is
displayed as “olleH”.

#include<stdio.h>
#include<string.h>
 int main()  Output:
{
   char name[30] = "Hello"; S
  printf("String before strrev( ) : %s\n",name); tr
  printf("String after strrev( )  : %s",strrev(name)); in
  return 0; g
} b
ef
or
e
st
rrev( ) : Hello
String after strrev( )     : olleH

C – strset() function

 strset( ) function sets all the characters in a string to given character.


 strset( ) function is non standard function which may not available in
standard library in C.

Example program for strset() function in C:

In this program, all characters of the string “Test String” is set to “#” using
strset( ) function and output is displayed as “###########”.

#include<stdio.h>
#include<string.h>
int main()
{
   char str[20] = "Test String";
   printf("Original string is : %s", str);
   printf("Test string after strset() : %s",strset(str,'#'));
   printf("After string set: %s",str);
   return 0;
}

Output:

Original string is             : Test String


Test string after strset() : ###########

C – strnset() function

 trnset( ) function sets portion of characters in a string to given character.


 strnset( ) function is non standard function which may not available in
standard library in C.

Example program for strnset() function in C:

In this program, first 4 characters of the string “Test String” is set to “#” using
strnset( ) function and output is displayed as “#### String”.

#include<stdio.h>
#include<string.h>
int main()
{
    char str[20] = "Test String";
    printf("Original string is : %s", str);
    printf("Test string after string n set" \
           " : %s", strnset(str,'#',4));
    printf("After string n set : %s", str);
    return 0;
}

Output:

Original string is                 : Test String


Test string after string set : #### String

Passing Strings to Functions

Strings are just char arrays. So, they can be passed to a function in a similar
manner as arrays.

#include <stdio.h>
void displayString(char str[]);

int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string c to function.
return 0;
}
void displayString(char str[]){
printf("String Output: ");
puts(str);
}

Here, string c is passed from main() function to user-defined function


displayString(). In function declaration, str[] is the formal argument.

You might also like