[go: up one dir, main page]

0% found this document useful (0 votes)
11 views13 pages

3rd Unit PDF

Uploaded by

pamidi.prameela
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views13 pages

3rd Unit PDF

Uploaded by

pamidi.prameela
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

A String in C programming is a sequence of characters terminated with a null character ‘\0’.

The C String
is stored as an array of characters. The difference between a character array and a C string is that the
string in C is terminated with a unique character ‘\0’.

Example:

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

C String Declaration Syntax


Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic syntax for
declaring a string.

char string_name[size];
In the above syntax string_name is any name given to the string variable and size is used to define the
length of the string, i.e the number of characters strings will store.

There is an extra terminating character which is the Null character (‘\0’) used to indicate the termination
of a string that differs strings from normal character arrays.

C String Initialization
A string in C can be initialized in different ways. We will explain this with the help of an example. Below
are the examples to declare a string with the name str and initialize it with “ C Programming”.

We can initialize a C string in 4 different ways which are as follows:

1. Assigning a String Literal without Size


String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is
an array.

Syntax:

char str[] = “ C Programming”;


2. Assigning a String Literal with a Predefined Size
String literals can be assigned with a predefined size. But we should always account for one extra space
which will be assigned to the null character. If we want to store a string of size n then we should always
declare a string with a size equal to or greater than n+1.

Syntax:

char str[50] = “ C Programming”;


3. Assigning Character by Character with Size
We can also assign a string character by character. But we should remember to set the end character as
‘\0’ which is a null character.

Syntax:

char str[12] = { 'c','p','r','o','g','m','m','i','n','g','\0'};


4. Assigning Character by Character without Size
We can assign character by character without size with the NULL character at the end. The size of the
string is determined by the compiler automatically.

Syntax:

char str[] = { 'c','p','r','o','g','m','m','i','n','g','\0'};


Note: When a Sequence of characters enclosed in the double quotation marks is encountered by the
compiler, a null character ‘\0’ is appended at the end of the string by default.

Program on strings:
// C program to illustrate strings

#include <stdio.h>

#include <string.h>

int main()

// declare and initialize string

char str[] = " C Programming";


// print string

printf("%s\n", str);

int length = 0;

length = strlen(str);

// displaying the length of string

printf("Length of string str is %d", length);

return 0;

Output:

C Programming
Length of string str is 12

 Different functions used for reading and writing strings with examples:
The user can input strings to the program via the console. There are three methods to read strings:

 Using scanf();
 Using getchar();
 Using gets();

Using scanf() functions:


You can use the scanf() function to read a string like any other data types. However, the scanf() function
only takes the first enterd word the function terminates when it encounters a white spave any string
before white spaces is only considered the format specifier to read string is %s.

Example:

Char place[10];

Scanf(“%s”,place);
Using getchar(); : getchar() function is used o tead successive single characters from the input and
place them into a character array.thus an entire line of text can be read and stored in an array.

The general form for getchar() function is as follows;

Char ch;

Ch = getchar( ); // note that getchar() has no parameters

Using gets( ) function : gets() function is available in the <stdio.h> header file this is a simple
function with one string parameter and called as follows:

 Gets(strings);

Str is a string variable declared properly.

For example:

Char name[20];

Gets(name);

Printf(“%s”,name);

Three functions used for writing strings:


The programmer can print strings from the program to the console. There are three methods to read
strings:

 Using printf();
 Using putchar();
 Using puts();

Using printf() functions: the printf function with %s format to print strings to the screen the format %s
can be used to display an array of characters that is terminated by the null character.

For example:

Printf(“%s”,name);

Program on printf()
Using putchar( ) function: like getchar( ), c supports another character handling function
putchar() to output the values of character variables it takes the following

syntax:

Char ch =A;

Putchar (ch); // the function purchar requires one parameter.

Using puts() function: The puts() function works exactly opposite to gets() function it outputs a
string to the scteen from memory that is from the array we declare until reaches the null character.

Syntax: puts(variable name);

Example : char name[20];

Gets(name);

Puts(name);

String manipulation functions :


The C string functions are built-in functions that can be used for various operations and manipulations
on strings. These string functions can be used to perform tasks such as string copy, concatenation,
comparison, length, etc. The <string.h> header file contains these string functions.

 strcat() Function
The strcat() function in C is used for string concatenation. It will append a copy of the source string to
the end of the destination string.

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

The terminating character at the end of dest is replaced by the first character of src.

Parameters

dest: Destination string

src: Source string

Return value

The strcat() function returns a pointer to the dest string.

Example
// C Program to illustrate the strcat function

#include <stdio.h>

int main()

char dest[50] = "This is an";

char src[50] = " example";

printf("dest Before: %s\n", dest);

// concatenating src at the end of dest

strcat(dest, src);

printf("dest After: %s", dest);

return 0;

Output:

dest Before: This is an

dest After: This is an example

2. strlen() Function
The strlen() function calculates the length of a given string. It doesn’t count the null character ‘\0’.

Syntax : int strlen(const char *str);

Parameters

str: It represents the string variable whose length we have to find.

Return Value

strlen() function in C returns the length of the string.

Example
// C program to demonstrate the strlen() function

#include <stdio.h>

#include <string.h>

int main()

// Declare and initialize a character array 'str' with

// the string "GeeksforGeeks"

char str[] = "GeeksforGeeks";

// Calculate the length of the string using the strlen()

// function and store it in the variable 'length'

size_t length = strlen(str);

// Print the length of the string

printf("String: %s\n", str);

printf("Length: %zu\n", length);

return 0;

Output

String: GeeksforGeeks

Length: 13

3. strcmp() Function
The strcmp() is a built-in library function in C. This function takes two strings as arguments and compares
these two strings lexicographically.

Syntax int strcmp(const char *str1, const char *str2);

Parameters

str1: This is the first string to be compared.

str2: This is the second string to be compared.


Return Value

If str1 is less than str2, the return value is less than 0.

If str1 is greater than str2, the return value is greater than 0.

If str1 is equal to str2, the return value is 0.

Example

// C program to demonstrate the strcmp() function

#include <stdio.h>

#include <string.h>

int main()

// Define a string 'str1' and initialize it with "Geeks"

char str1[] = "Geeks";

// Define a string 'str2' and initialize it with "For"

char str2[] = "For";

// Define a string 'str3' and initialize it with "Geeks"

char str3[] = "Geeks";

// Compare 'str1' and 'str2' using strcmp() function and

// store the result in 'result1'

int result1 = strcmp(str1, str2);

// Compare 'str2' and 'str3' using strcmp() function and

// store the result in 'result2'

int result2 = strcmp(str2, str3);

// Compare 'str1' and 'str1' using strcmp() function and

// store the result in 'result3'

int result3 = strcmp(str1, str1);


// Print the result of the comparison between 'str1' and

// 'str2'

printf("Comparison of str1 and str2: %d\n", result1);

// Print the result of the comparison between 'str2' and

// 'str3'

printf("Comparison of str2 and str3: %d\n", result2);

// Print the result of the comparison between 'str1' and

// 'str1'

printf("Comparison of str1 and str1: %d\n", result3);

return 0;

Output

Comparison of str1 and str2: 1

Comparison of str2 and str3: -1

Comparison of str1 and str1: 0

There is a function strncmp() similar to strcmp().

 strncmp()
This function lexicographically compares the first n characters from the two null-terminated strings and
returns an integer based on the outcome.

Syntax

int strncmp(const char* str1, const char* str2, size_t num);

Where num is the number of characters to compare.

4. strcpy
The strcpy() is a standard library function in C and is used to copy one string to another. In C, it is present
in <string.h> header file.

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

Parameters

dest: Pointer to the destination array where the content is to be copied.

src: string which will be copied.

Return Value

strcpy() function returns a pointer pointing to the output string.

Example

// C program to illustrate the use of strcpy()

#include <stdio.h>

#include <string.h>

int main()

// defining strings

char source[] = "GeeksforGeeks";

char dest[20];

// Copying the source string to dest

strcpy(dest, source);

// printing result

printf("Source: %s\n", source);

printf("Destination: %s\n", dest);

return 0;

Output

Source: GeeksforGeeks
Destination: GeeksforGeeks

 strncpy()
The function strncpy() is similar to strcpy() function, except that at most n bytes of src are copied.

If there is no NULL character among the first n character of src, the string placed in dest will not be
NULL-terminated. If the length of src is less than n, strncpy() writes an additional NULL character to dest
to ensure that a total of n characters are written.

Syntax

char* strncpy( char* dest, const char* src, size_t n );

Where n is the first n characters to be copied from src to dest.

 5. strchr()
The strchr() function in C is a predefined function used for string handling. This function is used to find
the first occurrence of a character in a string.

Syntax

char *strchr(const char *str, int c);

Parameters

str: specifies the pointer to the null-terminated string to be searched in.

ch: specifies the character to be searched for.

Here, str is the string and ch is the character to be located. It is passed as its int promotion, but it is
internally converted back to char.

Return Value

It returns a pointer to the first occurrence of the character in the string.

Example
#include <stdio.h>

#include <string.h>

int main()

char str[] = "GeeksforGeeks";


char ch = 'e';

// Search for the character 'e' in the string

// Use the strchr function to find the first occurrence

// of 'e' in the string

char* result = strchr(str, ch);

// Character 'e' is found, calculate the index by

// subtracting the result pointer from the str pointer

if (result != NULL) {

printf("The character '%c' is found at index %ld\n",

ch, result - str);

else {

printf("The character '%c' is not found in the "

"string\n",

ch);

return 0;

Output

The character 'e' is found at index 1

strrchr() Function
In C, strrchr() function is similar to strchr() function. This function is used to find the last occurrence of a
character in a string.

Syntax

char* strchr(const char *str, int ch);

You might also like