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

3 String

The document provides information on string operations in C programming. It defines what a string is, how to declare and initialize strings, and how to perform common string operations like length, concatenation, copying, reversing, substring, replacement, and comparison. It also discusses functions for reading, writing, and manipulating strings like printf, scanf, gets, puts, and built-in string functions. Example programs are provided to demonstrate reading, writing, concatenating, reversing, and extracting substrings from strings.

Uploaded by

Prem Kumar J
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

3 String

The document provides information on string operations in C programming. It defines what a string is, how to declare and initialize strings, and how to perform common string operations like length, concatenation, copying, reversing, substring, replacement, and comparison. It also discusses functions for reading, writing, and manipulating strings like printf, scanf, gets, puts, and built-in string functions. Example programs are provided to demonstrate reading, writing, concatenating, reversing, and extracting substrings from strings.

Uploaded by

Prem Kumar J
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT-3

STRINGS
SYLLABUS

 Introduction to Strings - Reading and writing a


string - String operations (without using built-in
string functions): Length – Compare –
Concatenate – Copy – Reverse – Substring –
Insertion – Indexing – Deletion – Replacement –
Array of strings – Introduction to Pointers –
Pointer operators – Pointer arithmetic - Exercise
programs: To find the frequency of a character in a
string - To find the number of vowels, consonants
and white spaces in a given text - Sorting the
names.
WHAT IS STRING?
 String is a one-dimensional array of
characters terminated by a null character '\
0'.
 a null character (‘\0’) is stored to signify the
end of the character array.
 Internal Representation:
 char c[] = “EINSTEIN COLLEGE";
E I N S T E I N C O L L E G E \0

 Length of the String is 16 (need 16+1


locations)
HOW TO DECLARE A STRING?
 A string can be declared as a character array
or with a string pointer
 datatype stringname[size];
 char s[10];// can store 9 characters
 char *s;
 Here, we have declared a string of 10
characters.
HOW TO INITIALIZE STRING?
 You can initialize strings in a number of ways.
 char str[] = “ECE";
 char str[5] = {‘E',‘C',‘E','\0'};
 char *s=“ECE"; // string pointer

E C E \0
S[0] S[1] S[2] S[3]
1000 1001 1002 1003
 String constants are enclosed in double quotes
 Character constants are enclosed in single quotes
 Illegal: char str[5] ;
str=“EINSTEIN";
Example program using Pointers
#include<stdio.h>
#include<string.h>
void main()
{
char *s=“Tirunelveli";
printf("%s\n",s);
printf("%c\n”,s);
printf("%c\n",*s);
printf("%c\n",*(s+4));
printf("%c\n",*s+5);
}
OUTPUT
Tirunelveli

T
n
Y
READING A STRING
 char str[25];
 String str can be read by 3 ways
 1.Using scanf() function
scanf(“%s”,str);
 It terminates as soon as it finds a blank space
 2.Using gets() function
gets(str);
 Takes the starting address, read the string and terminate
automatically with a null character.
 3.Using getchar() function
getchar(ch);
getch()
 getchar() as the name states it reads only one character at
a time.
 In order to read a string, we have to use this function
repeatedly until a terminating character is encountered.
 The characters scanned one after the other have to be
stored simultaneously into the character array.
WRITING A STRING
 Strings can be displayed on screen in 3 ways
 1.using printf() function
char str[]=“hello”
Printf(“%s”,str);
|hello|
use width and Precision specification also.
Printf(“%5.3s”,str); //print only 3 char & Right justified
| hel|
Printf(“%-5.3s”,str); //print only 3 char & Left justified
|hel |
WRITING A STRING
 2. using puts() function
char str[]=“hello”
puts(str);
|hello|
 3.using putchar() function
char str[]=“hello”
putchar(ch);
 putchar() as the name states prints only one
character at a time.
 In order to print a string, we have to use this
function repeatedly until a terminating
character is encountered.
EXAMPLE PROGRAM
 Read and Write strings using printf & scanf
#include<stdio.h>
void main()
{
char str[20];
printf("Enter your name: ");
scanf("%s", str);
printf("Hello, %s", str);
}
OUTPUT
Enter your name: Aravind
Hello, Aravind
EXAMPLE PROGRAM
 Read and print strings using the gets() and puts()
functions
#include<stdio.h>
void main()
{
char str[100];
printf("Enter any sentence: ");
gets(str);
printf("\nYou have entered:\n");
puts(str);
}
OUTPUT
Enter any sentence: Iam an Engineer
You have entered:
Iam an Engineer
EXAMPLE PROGRAM
 Read the strings using the getchar() function
#include <stdio.h>
void main()
{
char str[50], ch;
int i=0;
printf("Enter name: ");
while((ch=getchar())!='\n')
{
str[i] = ch;
i++;
}
str[i] ='\0';
printf("Entered Name is: %s", str);
}
OUTPUT
Enter name: EINStein
Entered name: EINStein
EXAMPLE PROGRAM
 print the strings using the putchar() function
#include <stdio.h>
void main()
{
char str[]=“Happy Birthday”;
int i=0;
while((str[i]!=‘\0')
{
Putchar(str[i]);
i++;
}
}
OUTPUT
Happy Birthday
STRING FUNCTIONS(BUILT-IN)
 strlen() - It returns the string's length.
 strnlen() - It returns length of the string if it
is less than the value specified for maxlen
(maximum length) otherwise it returns
maxlen value.
 strcmp() - It compares two strings and
returns 0 if the strings are the same.
 strncmp() - It compares two strings only to n
characters.
 strcat() - It concatenates two strings and
returns the concatenated string.
STRING FUNCTIONS
 strncat() - It concatenates n characters of
one string to another string.
 strcpy() - It copies one string into another.
 strncpy() - It copies the first n characters of
one string into another.
 strchr()- It finds out the first occurrence of a
given character in a string.
 strrchr() - It finds out the last occurrence of
a given character in a string.
 strstr() - It finds out the first occurrence of a
given string in a string.
STRING FUNCTIONS
 strnstr() - It finds out the first occurrence of
a given string in a string where the search is
limited to n characters.
 strrev()-Reverse the string
STRING OPERATIONS
 1.Length of the string
#include <stdio.h>
#include <string.h>
Void main()
{
char s[] = “Engineer";
int i;
for (i = 0; s[i] != '\0'; ++i);
printf("Length of the string: %d", i);
}
Output:
Length of the string:8
STRING OPERATIONS
 2.Concatenate the string
#include <stdio.h>
#include <string.h>
void main(){
char s1[100] = “Electronics and ", s2[] = “Communication"; int
length=0, j;
// store length of s1 in the length variable
while (s1[length] != '\0') {
++length; }
// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length) {
s1[length] = s2[j]; }
// terminating the s1 string s1[length] = '\0';
printf("After concatenation: ");
puts(s1);}
Output:
After concatenation: Electronics and Communication
STRING OPERATIONS
 3.Copy the string
#include <stdio.h>
#include <string.h>
void main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
gets(s1);
for (i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
}
Output:
Enter string s1: Einstein
String s2: Einstein
STRING OPERATIONS
 4.Reverse the string
#include<stdio.h>
#include<string.h>
void main() {
int i,n; char str[20];
printf("Enter the String to get reversed\n");
gets(str);
n=strlen(str);
printf("Reversed string is \n");
for(i=n-1;i>=0;i--)
{
printf("%c",str[i]);
}
}
Output:
Enter the String to get reversed
Final Year
Reversed string is
raeY laniF
STRING OPERATIONS
 5.Substring-A substring is itself a string that is part of a longer string
#include<stdio.h>
#include<string.h>
int main()
{
char string[1000], sub[1000]; int position, length, c = 0;
printf("Input a string\n");
gets(string);
printf("Enter the position and length of substring\n"); scanf("%d%d", &position, &length);
while (c < length)
{
sub[c] = string[position+c-1];
c++; }
sub[c] = '\0';
printf("Required substring is: %s", sub);
}
Output:
Input a string
Tamilnadu
Enter the position and length of substring
15
Required substring is: Tamil
STRING OPERATIONS
 6. Compare two strings
#include<stdio.h>
#include<string.h>
int main()
{
char string[1000], sub[1000]; int position, length, c = 0;
printf("Input a string\n");
gets(string);
printf("Enter the position and length of substring\n"); scanf("%d%d", &position, &length);
while (c < length)
{
sub[c] = string[position+c-1];
c++; }
sub[c] = '\0';
printf("Required substring is: %s", sub);
}
Output:
Input a string
Tamilnadu
Enter the position and length of substring
15
Required substring is: Tamil
Replacement
#include <stdio.h>
#include <string.h>
int main() {
char str[50], pat[50], new_str[50], rep_pat[50]; int i = 0, j = 0, k =
0, n = 0, copy_loop = 0, rep_index = 0;
printf("Enter the string:");
gets(str);
printf("Enter the pattern:");
gets(pat);
printf("Enter the replace pattern:");
gets(rep_pat);
while (str[i] != '\0')
{
j = 0; k = i;
while (str[k] == pat[j] && pat[j] != '\0')
{
k++;
j++;
}
if (pat[j] == '\0')
{
copy_loop = k;
while (rep_pat[rep_index] != '\0')
{
new_str[n] = rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n] = str[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n] = '\0';
printf("\nThe New String is:");
puts(new_str);
return 0;
}
#include <stdio.h>
#include <string.h>

int main() {
char originalString[100] = "Hello, world!";
char stringToInsert[] = " beautiful";
int insertionIndex = 6; // Index where you want to insert the new string

int originalLength = strlen(originalString);


int insertLength = strlen(stringToInsert);

// Shift the characters to make space for the new string


for (int i = originalLength; i >= insertionIndex; i--) {
originalString[i + insertLength] = originalString[i];
}

// Copy the new string into the original string


for (int i = 0; i < insertLength; i++) {
originalString[insertionIndex + i] = stringToInsert[i];
}

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

return 0;
}
 Hello, beautiful world!
INDEXING
 #include <stdio.h> int main()
 {
 char myString[] = "Hello, World!";
 // Accessing characters using indexing
 char firstChar = myString[0];
 char fifthChar = myString[4];
 printf("First character: %c\n", firstChar);
printf("Fifth character: %c\n", fifthChar);
return 0;
 }
Deletion
#include <stdio.h>
#include <string.h>
int main() {
char inputString[100];
char charToDelete;
printf("Enter a string: ");
scanf("%99s", inputString); // Read up to 99 characters to avoid buffer overflow
printf("Enter the character to delete: ");
scanf(" %c", &charToDelete); // Notice the space before %c to consume the newline
character from the previous input
int len = strlen(inputString);
char resultString[len]; // Create a new string to hold the result int j = 0; // Index
for the resultString
for (int i = 0; i < len; i++)
{ if (inputString[i] != charToDelete)
{ resultString[j] = inputString[i];
j++;
}}
resultString[j] = '\0'; // Null-terminate the resultString
printf("Original string: %s\n", inputString);
printf("String after deletion: %s\n", resultString);
return 0; }
POINTERS
INTRODUCTION
 In C, when we declare a variable, the
compiler allocates required memory with the
specified name.
 In C, every variable has a name, datatype,
value, and address.
 Accessing the Address of Variables
 weuse the reference operator "&" to access the
address of variable.
EXAMPLE
#include<stdio.h>
void main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var is:
%u\n", &var);
}
Output:
Value of the variable var is: 7
Memory address of the variable var is:
3493875900
WHAT IS A POINTER IN C?
 In C, we use a special type of variable called a
pointer to store the address of another
variable with the same datatype.
 A pointer is defined as follows...
 Pointer
is a special type of variable used to store
the memory location address of a variable.
 Declaring Pointers− datatype *pointerName ;
 *-Dereference operator
 Eg: int *ptr ;
 Thevariable "ptr" is a pointer variable that can be
used to store any integer variable address.
HOW TO USE POINTERS?
 Assigning Address to Pointer
 To assign address to a pointer variable we use
assignment operator with the following syntax...
 pointerVariableName = & variableName ;

int a, *ptr ;
variable "a" is a normal integer variable and
variable "ptr" is an integer pointer variable. If we
want to assign the address of variable "a" to
pointer variable "ptr" we use the following
statement...
ptr = &a ;
The address of variable "a" is assigned to pointer
variable "prt". Here we say that pointer
variable ptr is pointing to variable a.
 Accessing Variable Value Using Pointer
 Pointervariables are used to store the address of
other variables. We can use this address to
access the value of the variable through its
pointer. We use the symbol "*" infront of pointer
variable name to access the value of variable to
which the pointer is pointing.
EXAMPLE
#include<stdio.h>
void main()
{
int a = 10, *ptr ;
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
}
Output:
Address of variable a = 854998812
Value of variable a = 10
Address of variable ptr = 854998800
POINTER OPERATORS
 There are two pointer operators :
1. value at address operator ( * )
2. address of operator ( & )

1. Value at address operator ( * )


The * is a unary operator. It gives the value stored at a
particular address. The ‘value at address’ operator is also called
‘indirection’ operator.
q = *m;
if m contains the memory address of the variable count, then
preceding assignment statement can places the value of count into
q.

2. Address of operator ( & )


The & is a unary operator that returns the memory address of
its operand.
m = & count;
 The preceding assignment statement can be “The memory address
of the variable count is places into m”.
POINTER ARITHMETIC
 In the c programming language, we can
perform the following arithmetic operations
on pointers...
 Addition
 Subtraction
 Increment
 Decrement
 Comparison
 We can't perform multiplication and
division operations on pointers.
ADDITION
 In the c programming language, the addition
operation on pointer variables is calculated
using the following formula...
 AddressAtPointer
+ ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
#include<stdio.h>
void main()
{
float n = 10;
float *a;
a = &n;
printf("current address = %u \n",a);
a = a + 4;
printf("next address = %u \n",a);
}
Output
current address = 1534783284
next address = 1534783300
SUBTRACTION
 In the c programming language, the
subtraction operation on pointer variables is
calculated using the following formula...
 AddressAtPointer
- ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
#include<stdio.h>
void main()
{
float n = 10;
float *a;
a = &n;
printf("current address = %u \n",a);
a = a - 2;
printf("next address = %u \n",a);
}
Output:
current address = 3800540740
next address = 3800540732
INCREMENT
 The increment operation on pointer variable
is calculated as follows...
 AddressAtPointer
+
NumberOfBytesRequiresByDatatype
 The decrement operation on pointer variable
is calculated as follows...
 AddressAtPointer
-
NumberOfBytesRequiresByDatatype
#include<stdio.h>
void main()
{
double n = 10;
double *a;
a = &n;
printf("current address = %u \n",a);
a = a+1;
printf("next address = %u \n",a);
}
Output
current address = 2546642480
next address = 2546642488
#include<stdio.h>
void main()
{
float n = 10;
float *a;
a = &n;
printf("current address = %u \n",a);
a = a-1;
printf("next address = %u \n",a);
}
Output
current address = 3424537556
next address = 3424537552
COMPARISON
#include <stdio.h>
void main()
{
int *p2;
int *p1;
p2 = (int *)300;
p1 = (int *)200;
if(p1 > p2)
{
printf("P1 is greater than p2");
}
else
{ printf("P2 is greater than p1");
}
}
Output
P2 is greater than p1

You might also like