際際滷

際際滷Share a Scribd company logo
Module 4
Strings
Strings are defined as an array of characters. The difference
between a character array and a string is the string is terminated
with a special character 0.
Declaration of strings: Declaring a string is as simple as declaring a
one-dimensional array. Below is the basic syntax for declaring a string.
char str_name[size];
In the above syntax str_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. Please keep in mind that there is an extra
terminating character which is the Null character (0) used to indicate
the termination of string which differs strings from normal character
arrays.
Initializing a String:
// C program to illustrate strings
#include<stdio.h>
int main()
{
// declare and initialize string
char str[] = "cmrit";
// print string
printf("%s",str);
return 0;
}
// C program to see how scanf() stops reading input after whitespaces
#include <stdio.h>
int main()
{
char str[20];
printf("enter somethingn");
scanf("%s", str);
printf("you entered: %sn", str);
return 0;
}
Here the input will be provided by the user and output will be as
follows:
Input: Computer science
Output: Computer
gets()
It is used to read input from the standard input(keyboard).
It is used to read the input until it encounters newline or End Of File(EOF).
// C program to show how gets() takes whitespace as a string.
#include <stdio.h>
int main()
{
char str[20];
printf("enter somethingn");
gets(str);
printf("you entered : %sn", str);
return 0;
}
Here input will be provided by user as follows
Input: Computer science
Output: Computer science
C program to show how to read entire string using scanf()
#include <stdio.h>
int main()
{
char str[20];
printf("Enter somethingn");
// Here n indicates that take the input
// until newline is encountered
scanf("%[^n]s", str);
printf("%s", str);
return 0;
}
The above code reads the string until it encounters newline.
Examples:
Input: Computer science
Output: Computer science
Principals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdfModule-4.pdf
// C program to illustrate how to pass string to functions
#include<stdio.h>
void printStr(char str[])
{
printf("String is : %s",str);
}
int main()
{
// declare and initialize string
char str[] = "cmrit bangalore";
// print string by passing string
// to a different function
printStr(str);
return 0;
}
String Handling Functions
in C
These String functions are:
1. strlen().
2. strupr().
3. strlwr().
4. strcmp().
5. strcat().
6. strcpy().
7. strrev().
strlen()
size_t strlen(const char *str);
The function takes a single argument, i.e, the string variable whose
length is to be found, and returns the length of the string passed.
The strlen() function is defined in <string.h> header file
#include <stdio.h>
strlen()
#include <string.h>
int main()
{
char a*20+=Program
char b*20+=,P,r,o,g,r,a,m,0-;
char c[20];
printf(Enter string: );
gets(c);
printf(Length of string a = %d n, strlen(a));
printf(Length of string b = %d n, strlen(b));
printf(Length of string c = %d n, strlen(c));
return 0;}
strupr()
 strupr() function convertsa given string into uppercase. Syntax
for strupr( ) functionis given below.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Upper";
printf("%sn",strupr(str));
return 0;
}
Output: MODIFY THIS STRING TO UPPER
strlwr()
strlwr( ) function converts a given string into lowercase. Syntax for
strlwr( ) function is given below.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%sn",strlwr (str));
return 0;
}
OUTPUT: modify this string to lower
strcmp()
strcmp( ) function in C compares two given strings and returns zero if
they are same.
#include <stdio.h>
#include <string.h>
int main( )
{char str1[ ] = "fresh" ;
char str2[ ] = "refresh" ;
int i, j, k ;
i = strcmp ( str1, "fresh" ) ;
j = strcmp ( str1, str2 ) ;
k = strcmp ( str1, "f" ) ;
printf ( "n%d %d %d", i, j, k ) ;return 0;}
strcat()
strcat( ) function in C language concatenates two given strings. It
concatenates source string at the end of destinationstring.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " fresh2refresh" ;
char target[ ]= " C tutorial" ;
printf ( "nSource string = %s", source ) ;
printf ( "nTarget string = %s", target ) ;
strcat ( target, source ) ;
printf ( "nTarget string after strcat( ) = %s", target ) ;}
strcpy()
strcpy( ) function copies contents of one string into another string
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "nsource string = %s", source ) ;
printf ( "ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
strrev()
strrev( ) function reverses a given string in C language
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %sn",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}
Arrays of strings
 A string is a 1-D array of characters, so an array of strings is a 2-D
array of characters.
 Just like we can create a 2-D array of int, float etc; we canalso
create a 2-D array of character or array of strings.
Here is how we can declare a 2-D array of characters.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '0'},
{'t', 'o', 'm','0'},
{'j', 'e', 'r', 'r', 'y','0'}
};
 It is important to end each 1-D array by the null character
otherwise, it's just an array of characters. We can't use them as
strings.
 Declaring an array of string this way is a tedious and error-prone
process that's why C provides a more compact way to it. This above
initialization is equivalentto:
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
The following program demonstrates how to print an array
of strings.
#include<stdio.h>
int main()
{
int i;
char ch_arr[3][10] = {"spike","tom","jerry"};
printf("1st way nn");
for(i = 0; i < 3; i++)
{
printf("string = %s t address = %un", ch_arr + i, ch_arr + i);
}
signal to operating system program ran fine return 0;
}
String Manipulation Function
C String function  strlen
Syntax:
size_t strlen(const char *str)
size_t represents unsigned short
It returns the length of the string without including end character (terminating
char 0).
Example of strlen:
#include <stdio.h>
#include <string.h> int
main()
{
char str1[20] = "be happy";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:
Length of string str1: 8
strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns
the total allocated size assigned to the array. So if I consider the above example
again then the following statements would return the below values.
strlen(str1) returned value 13.
sizeof(str1) would return value 20 as the array size is 20
C String function  strcmp
int strcmp(const char *str1, const char *str2)
It compares the two strings and returns an integer value. If both the
strings are same (equal) then this function would return 0 otherwise it
may return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would
result in a negative value. If string1 > string2 then it would return
positive value.
If string1 == string2 then you would get 0(zero) when you use this
function for compare strings.
Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "bangalore";
char s2[20] = "hyderabad";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
string 1 and 2 are different
C String function  strcat
char *strcat(char *str1, char *str2)
It concatenates two strings and returns the concatenated string.
Example of strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
Output string after concatenation: HelloWorld
C String function  strcpy
char *strcpy( char *str1, char *str2)
It copies the string str2 into string str1, including the end character (terminator
char 0).
Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : Im gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
String s1 is: string 2: Im gonna copied into s1
Passing string to Function
C program to pass a string to a function
#include <stdio.h>
void Strfun(char *ptr)
{
printf("The String is : %s",ptr);
}
// main function
int main()
{
// Declare a buffer of type "char"
char buff[20]="Hello Function";
// Passing string to Function
Strfun(buff);
return 0;
}
Passing string to Function
C program to pass a string to a function
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
String Manipulation without using built-in function
(Using user defined function)
Calculate string length
#include <stdio.h>
/*function to return length of the string*/
int stringLength(char*);
int main()
{
char str[100]={0};
int length;
printf("Enter any string: ");
scanf("%s",str);
/*call the function*/
length=stringLength(str);
printf("String length is : %dn",length);
/*function definition...*/
int stringLength(char* txt)
{
int i=0,count=0;
while(txt[i++]!='0'){
count+=1;
}
return count;
}
return 0;
}
program to copy one string to another (implementation of strcpy) in C
#include <stdio.h>
void stringCpy(char* s1,char* s2);
int main()
{
char str1[100],str2[100];
printf("Enter string 1: ");
scanf("%[^n]s",str1);//read string with spaces
stringCpy(str2,str1);
printf("String 1: %s nString 2: %sn",str1,str2);
return 0;
}
/*** function definition **/
void stringCpy(char* s1,char* s2)
{
int i=0;
while(s2[i]!='0')
{
s1[i]=s2[i];
i++;
}
s1[i]='0'; /*string terminates by
NULL*/
}
C program to concatenate two strings without using library function
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
void stringCat (char *s1,char *s2);
int main()
{
char str1[MAX_SIZE],str2[MAX_SIZE];
printf("Enter string 1 : ");
scanf("%[^n]s",str1);//read string with spaces
getchar();//read enter after entering first string
printf("Enter string 2 : ");
scanf("%[^n]s",str2);//read string with spaces
stringCat(str1,str2);
printf("nAfter concatenate strings are :n");
printf("String 1: %s nString 2: %s",str1,str2);
printf("n");
return 0;
}
/*** function definition **/
void stringCat (char *s1,char *s2)
{
int len,i;
len=strlen(s1)+strlen(s2);
if(len>MAX_SIZE)
{
printf("nCan not Concatenate !!!");
return;
}
len=strlen(s1);
for(i=0;i< strlen(s2); i++)
{
s1[len+i]=s2[i];
}
s1[len+i]='0'; /* terminates by NULL*/
}
String comparison without using strcmp() function
#include <stdio.h>
int compare(char[],char[]);
int main()
{
char str1[20]; // declaration of char array
char str2[20]; // declaration of char array
printf("Enter the first string : ");
scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);
int c= compare(str1,str2); // calling compare() function
if(c==0)
printf("strings are same");
else
printf("strings are not same");
return 0;
}
// Comparing both the strings.
int compare(char a[],char b[])
{
int flag=0,i=0; // integer variables declaration
while(a[i]!='0' &&b[i]!='0') // while loop
{
if(a[i]!=b[i])
{
flag=1;
break;
}
i++;
}
if(flag==0)
return 0;
else
return 1;
}
Given a string and we have to count digits, spaces, special characters and alphabets using
C program.
#include <stdio.h>
int main()
{
char str[100];
int countDigits, countAlphabet, countSpecialChar, countSpaces;
int counter;
//assign all counters to zero
countDigits = countAlphabet = countSpecialChar = countSpaces = 0;
printf("Enter a string: ");
gets(str);
for (counter = 0; str[counter] != NULL; counter++) {
if (str[counter] >= '0' && str[counter] <= '9')
countDigits++;
else if ((str[counter] >= 'A' && str[counter] <= 'Z') || (str[counter] >= 'a' &&
str[counter] <= 'z'))
countAlphabet++;
else if (str[counter] == ' ')
countSpaces++;
else
countSpecialChar++;
}
printf("nDigits: %d nAlphabets: %d nSpaces: %d nSpecial Characters: %d",
countDigits, countAlphabet, countSpaces, countSpecialChar);
return 0;
}
Reverse a string without using library function
/*copy characters from last index of str and
#include <stdio.h>
#include <string.h>
int main()
{
store it from starting in revStr*/
j=0;
for(i=(strlen(str)-1); i>=0;i--)
revStr[j++]=str[i];
char str[100],revStr[100];
int i,j;
printf("Enter a string: ");
scanf("%[^n]s",str);//read string with
spaces
//assign NULL in the revStr
revStr[j]='0';
printf("nOriginal String is: %s",str);
printf("nReversed String is: %s",revStr);
return 0;
}
Pointer
A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location. Like any
variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable
declaration is 
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type
andvar-nameis the nameof the pointer variable.
Pointer
 The asterisk * used to declare a pointer is the same
asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a
variable as a pointer. Take a look at some of the valid
pointer declarations 
 int *ip; /* pointer to an integer */
 double *dp; /* pointer to a double */
 float *fp; /* pointer to a float */
 char *ch /* pointer to a character */
Pointer
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x", ip );
/* access the value using the pointer */
printf("Value of var variable: %d", *ip );
return 0;
}
Output:
Address of var variable: bffd8b3c
Value of var variable: 20
NULL Pointers
It is always a good practice to assign a NULL value to a pointer
variable in case you do not have an exact address to be assigned.
This is done at the time of variable declaration. A pointer that is
assignedNULL iscaled anull pointer.
The NULL pointer is a constant with a value of zero defined in
several standard libraries. Consider the following program 
#include <stdio.h>
int main () {
int *ptr ;
ptr=NULL;
printf("The value of ptr is : %xn", ptr );
return 0;
}
C dereference pointer
As we already know that "what is a pointer", a pointer is a variable
that stores the address of another variable. The dereference
operator is also known as an indirection operator, which is
represented by (*). When indirection operator (*) is used with the
pointer variable, then it is known as dereferencing a pointer.
When we dereference a pointer, then the value of the variable
pointed by this pointer will be returned.
Dereference apointer is used becauseof the following reasons:
It can be used to access or manipulate the data stored at the memory
location, which is pointed by the pointer.
Any operation applied to the dereferenced pointer will directly affect the
value of the variable that it points to.
Using Pointer concept Swap2 values( without usingthird Variable)
#include<stdio.h>
int main()
{
int a=10;
int b=20;
int *p, *q;
p=&a;
q=&b;
*p=*p+*q;
*q=*p-*q;
*p=*p-*q;
printf(after swapping
values of a=%d, b=%d, *p,
*q);
return 0;
}
Pointer Arithmetic in C with Examples
Pointers variables are also known as address data types because
they are used to store the address of another variable. The address
is the memory location that is assigned to the variable. It doesnt
store any value.
Hence, there are only a few operations that are allowed to perform
on Pointers in C language. The operations are slightly different from
the ones that we general y use for mathematical calculations. The
operations are:
 Increment/Decrement of aPointer
 Addition of integer to apointer
 Subtractionof integer to apointer
 Subtractingtwo pointers of the sametype
Increment/Decrement of aPointer
Increment: It is a condition that also comes under addition. When a
pointer is incremented, it actually increments by the number equal
to the size of the data type for which it is apointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it
will increment by 2(size of an int) and the new address it will points
to 1002. While if a float type pointer is incremented then it will
increment by 4(size of afloat) andthe new address will be 1004.
Samefor decrement of apointer
// C program to illustrate pointer increment/decrement
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Incrementing pointer ptr1;
ptr1++;
printf("Pointer ptr1 after"
" Increment: ");
printf("%p nn", ptr1);
// Pointer to an integer
int *ptr1, *ptr2;
printf("Pointer ptr1 before"
" Decrement: ");
// Pointer stores
// the address of N
ptr1 = &N;
ptr2 = &N;
printf("%p n", ptr1);
// Decrementing pointer ptr1;
ptr1--;
Output:
printf("Pointer ptr1 "
"before Increment: ");
printf("%p n", ptr1);
}
printf("Pointer ptr1 after"
" Decrement: ");
printf("%p nn", ptr1);
return 0;
Pointer ptr1 before Increment: 0x7ffcb19385e4
Pointer ptr1 after Increment: 0x7ffcb19385e8
Pointer ptr1 before Decrement: 0x7ffcb19385e8
Pointer ptr1 after Decrement: 0x7ffcb19385e4
When a pointer is added with a value, the value is first multiplied by the size of data type and
then added to the pointer.
// C program to illustrate pointer Addition
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after
Addition: ");
printf("%p n", ptr2);
return 0;
}
Output:
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
Pointer ptr2 before Addition:
0x7fffffdcd984
Pointer ptr2 after Addition:
0x7fffffdcd990
printf("Pointer ptr2 before Addition: ");
printf("%p n", ptr2);
When a pointer is subtracted with a value, the value is first multiplied by the size of the
data type and then subtracted from the pointer.
// C program to illustrate pointer Subtraction
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
printf("Pointer ptr2 after Subtraction: ");
printf("%p n", ptr2);
return 0;
}
Output:
Pointer ptr2 before Subtraction: 0x7ffcf1221b24
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
Pointer ptr2 after Subtraction: 0x7ffcf1221b18
printf("Pointer ptr2 before Subtraction: ");
printf("%p n", ptr2);
Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data
type. The result is generated by calculating the difference between the
addresses of the two pointers and calculating how many bits of data it is
according to the pointer data type. The subtraction of two pointers gives the
increments between the two pointers.
For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are
subtracted. The difference between address is 16 bytes. Since the size of int is
2 bytes, therefore the increment between ptr1 and ptr2 is given by (16/2) = 8.
Below is the implementation to illustrate the Subtraction of Two Pointers:
C program to illustrate Subtraction of two
pointers
#include <stdio.h>
// Driver Code
int main()
{
int x;
// Integer variable
int N = 4;
// Subtraction of ptr2 and ptr1
x = ptr2 - ptr1;
// Print x to get the Increment
// between ptr1 and ptr2
printf("Subtraction of ptr1 "
"& ptr2 is %dn", x);
// Pointer to an integer
int *ptr1, *ptr2;
return 0;
}
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
Output:
Subtraction of ptr1 & ptr2 is 3
// Incrementing ptr2 by 3
ptr2 = ptr2 + 3;
Pointers as function arguments
Pointer preliminaries:
Pointer Definition:
A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location. Like any variable or
constant, you must declare a pointer before using it to store any
variableaddress.
Function basics:
A function is a group of statements that together perform a task.
Every C program has at least one function, which is main(), and all the
most trivial programs can define additionalfunctions.
A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides theactual
body of the function.
Principals of Programming in CModule -5.pdfModule-4.pdf
Call by value
This method copies the actual value of an argument
parameter of the function.
into the formal
In this case, changes made to the parameter inside the function
have no effect on the argument.
Syntax:
Datatype function_name(datatype variable_name);
#include <stdio.h>
void swap(int i, int j)
{
int t; t=i; i=j; j=t;
}
void main()
{
int a,b;
a=5; b=10;
printf("%d %dn", a, b);
swap(a,b);
printf("%d %dn", a, b);
}
Call by reference:
This method copies the address of an
parameter.
argument into the formal
Inside the function, the address is used to
argument used in the call.
access the actual
This means that changes made to the parameter affect the
argument.
Syntax:
datatype function_name(datatype *variable_name);
Call by reference Example
#include <stdio.h> void swap(int
*i, int *j)
{
int t; t = *i;
*i = *j;
*j = t;
}
void main()
{
int a,b; a=5; b=10;
printf("%d %dn",a,b);
swap(&a,&b); printf("%d
%dn",a,b);
}
 When we pass a pointer as an argument instead of a variable then
the address of the variable is passed instead of thevalue.
 So any change made by the function using the pointer is
permanently made at the address of passed variable.
#include <stdio.h>
void salaryhike(int *var, int b)
{
*var = *var+b;
}
int main()
{
int salary=0, bonus=0;
printf("Enter the employee current salary:");
scanf("%d", &salary);
printf("Enter bonus:");
scanf("%d", &bonus);
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
return 0;
}
Example for passing pointers as function argument
#include<stdio.h>
#include<conio.h>
void getDoubleValue(int *F){
*F = *F + 2;
printf("F(Formal Parameter) = %dn", *F);
}
int main(){
int A;
printf("Enter a numbersn");
scanf("%d", &A);
getDoubleValue(&A);
printf("A(ActualParameter) = %dn", A);
getch();
}
Another Example on passing pointer to function
#include <stdio.h> int* larger(int*, int*); void main()
{
Int a = 15; int b = 92; int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
returny;
}
OUTPUT:
92 is larger
Functions of returning pointers
It is also possible for functions to return a function pointer as a
value.
 This ability increases the flexibility of programs.
In this case you must be careful, because local variables of function
doesn't live outside the function. They have scope only inside the
function.
Hence if you return a pointer connected to a local variable, that
pointer will be pointing to nothing when the function ends
Pointer to functions
Exampleof function pointers as returnedvalues
#include <stdio.h>
int* larger(int*, int*);
voidmain()
{
int a = 15; int b = 92; int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y) return x;
else
return y;
}

More Related Content

Similar to Principals of Programming in CModule -5.pdfModule-4.pdf (20)

Lecture 2. mte 407
Lecture 2. mte 407Lecture 2. mte 407
Lecture 2. mte 407
rumanatasnim415
C string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CGC string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CG
drsomeshdewangan
String class and function for b.tech iii year students
String class and function  for b.tech iii year studentsString class and function  for b.tech iii year students
String class and function for b.tech iii year students
Somesh Kumar
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
14 strings
14 strings14 strings
14 strings
Rohit Shrivastava
Strings IN C
Strings IN CStrings IN C
Strings IN C
yndaravind
Strings
StringsStrings
Strings
Imad Ali
Strings
StringsStrings
Strings
Mitali Chugh
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
strings
stringsstrings
strings
teach4uin
Module-2_Strings concepts in c programming
Module-2_Strings concepts in c programmingModule-2_Strings concepts in c programming
Module-2_Strings concepts in c programming
CHAITRAB29
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
mathesh0303
string , pointer
string , pointerstring , pointer
string , pointer
Arafat Bin Reza
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
c programming
c programmingc programming
c programming
Arun Umrao
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
C q 3
C q 3C q 3
C q 3
Rahul Vishwakarma
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
Strings part2
Strings part2Strings part2
Strings part2
yndaravind
C string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CGC string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CG
drsomeshdewangan
String class and function for b.tech iii year students
String class and function  for b.tech iii year studentsString class and function  for b.tech iii year students
String class and function for b.tech iii year students
Somesh Kumar
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
Strings IN C
Strings IN CStrings IN C
Strings IN C
yndaravind
Strings
StringsStrings
Strings
Imad Ali
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
Module-2_Strings concepts in c programming
Module-2_Strings concepts in c programmingModule-2_Strings concepts in c programming
Module-2_Strings concepts in c programming
CHAITRAB29
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
mathesh0303
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
c programming
c programmingc programming
c programming
Arun Umrao
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
Strings part2
Strings part2Strings part2
Strings part2
yndaravind

More from anilcsbs (6)

Principals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdfPrincipals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdf
anilcsbs
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdfPrincipals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
anilcsbs
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
Module 2_PPT_P1 POP Notes module 2 fdfd.pdfModule 2_PPT_P1 POP Notes module 2 fdfd.pdf
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
anilcsbs
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdfModule 1_Chapter 2_PPT (1)sasaddsdsds.pdf
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
anilcsbs
Principals of Programming in CModule -5.pdf
Principals of Programming in CModule -5.pdfPrincipals of Programming in CModule -5.pdf
Principals of Programming in CModule -5.pdf
anilcsbs
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
Module 1 _Chapter 1_PPT (1) (1) POP .pdfModule 1 _Chapter 1_PPT (1) (1) POP .pdf
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
anilcsbs
Principals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdfPrincipals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdf
anilcsbs
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdfPrincipals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
anilcsbs
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
Module 2_PPT_P1 POP Notes module 2 fdfd.pdfModule 2_PPT_P1 POP Notes module 2 fdfd.pdf
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
anilcsbs
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdfModule 1_Chapter 2_PPT (1)sasaddsdsds.pdf
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
anilcsbs
Principals of Programming in CModule -5.pdf
Principals of Programming in CModule -5.pdfPrincipals of Programming in CModule -5.pdf
Principals of Programming in CModule -5.pdf
anilcsbs
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
Module 1 _Chapter 1_PPT (1) (1) POP .pdfModule 1 _Chapter 1_PPT (1) (1) POP .pdf
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
anilcsbs

Recently uploaded (20)

PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
yadavchandan322
Smart wearable device for for health monitering
Smart wearable device for for health moniteringSmart wearable device for for health monitering
Smart wearable device for for health monitering
Venky1435
4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...
4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...
4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...
adityaprakashme26
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANEAirport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Priyanka Dange
MODULE 01 - CLOUD COMPUTING [BIS 613D] .pptx
MODULE 01 - CLOUD COMPUTING [BIS 613D] .pptxMODULE 01 - CLOUD COMPUTING [BIS 613D] .pptx
MODULE 01 - CLOUD COMPUTING [BIS 613D] .pptx
Alvas Institute of Engineering and technology, Moodabidri
Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...
Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...
Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...
josephmigliorini1
Final Round of technical quiz on Chandrayaan
Final Round of technical quiz on ChandrayaanFinal Round of technical quiz on Chandrayaan
Final Round of technical quiz on Chandrayaan
kamesh sonti
Shallow base metal exploration in northern New Brunswick.pdf
Shallow base metal exploration in northern New Brunswick.pdfShallow base metal exploration in northern New Brunswick.pdf
Shallow base metal exploration in northern New Brunswick.pdf
DUSABEMARIYA
OFFICE AUTOMATION USING ESP32 AND ESP RAINMAKER
OFFICE AUTOMATION USING ESP32 AND ESP RAINMAKEROFFICE AUTOMATION USING ESP32 AND ESP RAINMAKER
OFFICE AUTOMATION USING ESP32 AND ESP RAINMAKER
AdityaSK5
Transformer ppt for micro-teaching (2).pptx
Transformer ppt for micro-teaching (2).pptxTransformer ppt for micro-teaching (2).pptx
Transformer ppt for micro-teaching (2).pptx
GetahunShankoKefeni
BUILD WITH AI for GDG on campus MVJCE.pptx
BUILD WITH AI for GDG on campus MVJCE.pptxBUILD WITH AI for GDG on campus MVJCE.pptx
BUILD WITH AI for GDG on campus MVJCE.pptx
greeshmadj0
BCS401 ADA First IA Test Question Bank.pdf
BCS401 ADA First IA Test Question Bank.pdfBCS401 ADA First IA Test Question Bank.pdf
BCS401 ADA First IA Test Question Bank.pdf
VENKATESHBHAT25
Virtual Power plants-Cleantech-Revolution
Virtual Power plants-Cleantech-RevolutionVirtual Power plants-Cleantech-Revolution
Virtual Power plants-Cleantech-Revolution
Ashoka Saket
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptxUHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
arivazhaganrajangam
Introduction to CLoud Computing Technologies
Introduction to CLoud Computing TechnologiesIntroduction to CLoud Computing Technologies
Introduction to CLoud Computing Technologies
cloudlab1
power system protection and why to protect the system
power system protection and why to protect the systempower system protection and why to protect the system
power system protection and why to protect the system
DivyangBhatt6
Supervised Learning Ensemble Techniques Machine Learning
Supervised Learning Ensemble Techniques Machine LearningSupervised Learning Ensemble Techniques Machine Learning
Supervised Learning Ensemble Techniques Machine Learning
ShivarkarSandip
Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...
Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...
Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...
Alberto Lorenzo
Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...
Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...
Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...
Long Vo
Industry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and BeyondIndustry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and Beyond
GtxDriver
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...
yadavchandan322
Smart wearable device for for health monitering
Smart wearable device for for health moniteringSmart wearable device for for health monitering
Smart wearable device for for health monitering
Venky1435
4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...
4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...
4. "Exploring the Role of Lubrication in Machinery Efficiency: Mechanisms, Ty...
adityaprakashme26
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANEAirport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Airport Components Part1 ppt.pptx-Site layout,RUNWAY,TAXIWAY,TAXILANE
Priyanka Dange
Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...
Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...
Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...
josephmigliorini1
Final Round of technical quiz on Chandrayaan
Final Round of technical quiz on ChandrayaanFinal Round of technical quiz on Chandrayaan
Final Round of technical quiz on Chandrayaan
kamesh sonti
Shallow base metal exploration in northern New Brunswick.pdf
Shallow base metal exploration in northern New Brunswick.pdfShallow base metal exploration in northern New Brunswick.pdf
Shallow base metal exploration in northern New Brunswick.pdf
DUSABEMARIYA
OFFICE AUTOMATION USING ESP32 AND ESP RAINMAKER
OFFICE AUTOMATION USING ESP32 AND ESP RAINMAKEROFFICE AUTOMATION USING ESP32 AND ESP RAINMAKER
OFFICE AUTOMATION USING ESP32 AND ESP RAINMAKER
AdityaSK5
Transformer ppt for micro-teaching (2).pptx
Transformer ppt for micro-teaching (2).pptxTransformer ppt for micro-teaching (2).pptx
Transformer ppt for micro-teaching (2).pptx
GetahunShankoKefeni
BUILD WITH AI for GDG on campus MVJCE.pptx
BUILD WITH AI for GDG on campus MVJCE.pptxBUILD WITH AI for GDG on campus MVJCE.pptx
BUILD WITH AI for GDG on campus MVJCE.pptx
greeshmadj0
BCS401 ADA First IA Test Question Bank.pdf
BCS401 ADA First IA Test Question Bank.pdfBCS401 ADA First IA Test Question Bank.pdf
BCS401 ADA First IA Test Question Bank.pdf
VENKATESHBHAT25
Virtual Power plants-Cleantech-Revolution
Virtual Power plants-Cleantech-RevolutionVirtual Power plants-Cleantech-Revolution
Virtual Power plants-Cleantech-Revolution
Ashoka Saket
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptxUHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
UHV Unit - 4 HARMONY IN THE NATURE AND EXISTENCE.pptx
arivazhaganrajangam
Introduction to CLoud Computing Technologies
Introduction to CLoud Computing TechnologiesIntroduction to CLoud Computing Technologies
Introduction to CLoud Computing Technologies
cloudlab1
power system protection and why to protect the system
power system protection and why to protect the systempower system protection and why to protect the system
power system protection and why to protect the system
DivyangBhatt6
Supervised Learning Ensemble Techniques Machine Learning
Supervised Learning Ensemble Techniques Machine LearningSupervised Learning Ensemble Techniques Machine Learning
Supervised Learning Ensemble Techniques Machine Learning
ShivarkarSandip
Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...
Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...
Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...
Alberto Lorenzo
Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...
Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...
Artificial Neural Network to Identify Verical Fractured Wells Flow Period (Lo...
Long Vo
Industry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and BeyondIndustry 4.0: Transforming Modern Manufacturing and Beyond
Industry 4.0: Transforming Modern Manufacturing and Beyond
GtxDriver

Principals of Programming in CModule -5.pdfModule-4.pdf

  • 1. Module 4 Strings Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character 0.
  • 2. Declaration of strings: Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_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. Please keep in mind that there is an extra terminating character which is the Null character (0) used to indicate the termination of string which differs strings from normal character arrays.
  • 3. Initializing a String: // C program to illustrate strings #include<stdio.h> int main() { // declare and initialize string char str[] = "cmrit"; // print string printf("%s",str); return 0; }
  • 4. // C program to see how scanf() stops reading input after whitespaces #include <stdio.h> int main() { char str[20]; printf("enter somethingn"); scanf("%s", str); printf("you entered: %sn", str); return 0; } Here the input will be provided by the user and output will be as follows: Input: Computer science Output: Computer
  • 5. gets() It is used to read input from the standard input(keyboard). It is used to read the input until it encounters newline or End Of File(EOF). // C program to show how gets() takes whitespace as a string. #include <stdio.h> int main() { char str[20]; printf("enter somethingn"); gets(str); printf("you entered : %sn", str); return 0; } Here input will be provided by user as follows Input: Computer science Output: Computer science
  • 6. C program to show how to read entire string using scanf() #include <stdio.h> int main() { char str[20]; printf("Enter somethingn"); // Here n indicates that take the input // until newline is encountered scanf("%[^n]s", str); printf("%s", str); return 0; } The above code reads the string until it encounters newline. Examples: Input: Computer science Output: Computer science
  • 10. // C program to illustrate how to pass string to functions #include<stdio.h> void printStr(char str[]) { printf("String is : %s",str); } int main() { // declare and initialize string char str[] = "cmrit bangalore"; // print string by passing string // to a different function printStr(str); return 0; }
  • 11. String Handling Functions in C These String functions are: 1. strlen(). 2. strupr(). 3. strlwr(). 4. strcmp(). 5. strcat(). 6. strcpy(). 7. strrev().
  • 12. strlen() size_t strlen(const char *str); The function takes a single argument, i.e, the string variable whose length is to be found, and returns the length of the string passed. The strlen() function is defined in <string.h> header file
  • 13. #include <stdio.h> strlen() #include <string.h> int main() { char a*20+=Program char b*20+=,P,r,o,g,r,a,m,0-; char c[20]; printf(Enter string: ); gets(c); printf(Length of string a = %d n, strlen(a)); printf(Length of string b = %d n, strlen(b)); printf(Length of string c = %d n, strlen(c)); return 0;}
  • 14. strupr() strupr() function convertsa given string into uppercase. Syntax for strupr( ) functionis given below. #include<stdio.h> #include<string.h> int main() { char str[ ] = "Modify This String To Upper"; printf("%sn",strupr(str)); return 0; } Output: MODIFY THIS STRING TO UPPER
  • 15. strlwr() strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is given below. #include<stdio.h> #include<string.h> int main() { char str[ ] = "MODIFY This String To LOwer"; printf("%sn",strlwr (str)); return 0; } OUTPUT: modify this string to lower
  • 16. strcmp() strcmp( ) function in C compares two given strings and returns zero if they are same. #include <stdio.h> #include <string.h> int main( ) {char str1[ ] = "fresh" ; char str2[ ] = "refresh" ; int i, j, k ; i = strcmp ( str1, "fresh" ) ; j = strcmp ( str1, str2 ) ; k = strcmp ( str1, "f" ) ; printf ( "n%d %d %d", i, j, k ) ;return 0;}
  • 17. strcat() strcat( ) function in C language concatenates two given strings. It concatenates source string at the end of destinationstring. #include <stdio.h> #include <string.h> int main( ) { char source[ ] = " fresh2refresh" ; char target[ ]= " C tutorial" ; printf ( "nSource string = %s", source ) ; printf ( "nTarget string = %s", target ) ; strcat ( target, source ) ; printf ( "nTarget string after strcat( ) = %s", target ) ;}
  • 18. strcpy() strcpy( ) function copies contents of one string into another string #include <stdio.h> #include <string.h> int main( ) { char source[ ] = "fresh2refresh" ; char target[20]= "" ; printf ( "nsource string = %s", source ) ; printf ( "ntarget string = %s", target ) ; strcpy ( target, source ) ; printf ( "ntarget string after strcpy( ) = %s", target ) ; return 0; }
  • 19. strrev() strrev( ) function reverses a given string in C language #include<stdio.h> #include<string.h> int main() { char name[30] = "Hello"; printf("String before strrev( ) : %sn",name); printf("String after strrev( ) : %s",strrev(name)); return 0; }
  • 20. Arrays of strings A string is a 1-D array of characters, so an array of strings is a 2-D array of characters. Just like we can create a 2-D array of int, float etc; we canalso create a 2-D array of character or array of strings. Here is how we can declare a 2-D array of characters. char ch_arr[3][10] = { {'s', 'p', 'i', 'k', 'e', '0'}, {'t', 'o', 'm','0'}, {'j', 'e', 'r', 'r', 'y','0'} };
  • 21. It is important to end each 1-D array by the null character otherwise, it's just an array of characters. We can't use them as strings. Declaring an array of string this way is a tedious and error-prone process that's why C provides a more compact way to it. This above initialization is equivalentto: char ch_arr[3][10] = { "spike", "tom", "jerry" };
  • 22. The following program demonstrates how to print an array of strings. #include<stdio.h> int main() { int i; char ch_arr[3][10] = {"spike","tom","jerry"}; printf("1st way nn"); for(i = 0; i < 3; i++) { printf("string = %s t address = %un", ch_arr + i, ch_arr + i); } signal to operating system program ran fine return 0; }
  • 24. C String function strlen Syntax: size_t strlen(const char *str) size_t represents unsigned short It returns the length of the string without including end character (terminating char 0). Example of strlen: #include <stdio.h> #include <string.h> int main() { char str1[20] = "be happy"; printf("Length of string str1: %d", strlen(str1)); return 0; } Output: Length of string str1: 8
  • 25. strlen vs sizeof strlen returns you the length of the string stored in array, however sizeof returns the total allocated size assigned to the array. So if I consider the above example again then the following statements would return the below values. strlen(str1) returned value 13. sizeof(str1) would return value 20 as the array size is 20
  • 26. C String function strcmp int strcmp(const char *str1, const char *str2) It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison. If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2 then it would return positive value. If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
  • 27. Example of strcmp: #include <stdio.h> #include <string.h> int main() { char s1[20] = "bangalore"; char s2[20] = "hyderabad"; if (strcmp(s1, s2) ==0) { printf("string 1 and string 2 are equal"); }else { printf("string 1 and 2 are different"); } return 0; } Output: string 1 and 2 are different
  • 28. C String function strcat char *strcat(char *str1, char *str2) It concatenates two strings and returns the concatenated string. Example of strcat: #include <stdio.h> #include <string.h> int main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("Output string after concatenation: %s", s1); return 0; } Output: Output string after concatenation: HelloWorld
  • 29. C String function strcpy char *strcpy( char *str1, char *str2) It copies the string str2 into string str1, including the end character (terminator char 0). Example of strcpy: #include <stdio.h> #include <string.h> int main() { char s1[30] = "string 1"; char s2[30] = "string 2 : Im gonna copied into s1"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); return 0; } Output: String s1 is: string 2: Im gonna copied into s1
  • 30. Passing string to Function C program to pass a string to a function #include <stdio.h> void Strfun(char *ptr) { printf("The String is : %s",ptr); } // main function int main() { // Declare a buffer of type "char" char buff[20]="Hello Function"; // Passing string to Function Strfun(buff); return 0; }
  • 31. Passing string to Function C program to pass a string to a function #include <stdio.h> void displayString(char str[]); int main() { char str[50]; printf("Enter string: "); fgets(str, sizeof(str), stdin); displayString(str); // Passing string to a function. return 0; } void displayString(char str[]) { printf("String Output: "); puts(str); }
  • 32. String Manipulation without using built-in function (Using user defined function) Calculate string length #include <stdio.h> /*function to return length of the string*/ int stringLength(char*); int main() { char str[100]={0}; int length; printf("Enter any string: "); scanf("%s",str); /*call the function*/ length=stringLength(str); printf("String length is : %dn",length); /*function definition...*/ int stringLength(char* txt) { int i=0,count=0; while(txt[i++]!='0'){ count+=1; } return count; } return 0; }
  • 33. program to copy one string to another (implementation of strcpy) in C #include <stdio.h> void stringCpy(char* s1,char* s2); int main() { char str1[100],str2[100]; printf("Enter string 1: "); scanf("%[^n]s",str1);//read string with spaces stringCpy(str2,str1); printf("String 1: %s nString 2: %sn",str1,str2); return 0; } /*** function definition **/ void stringCpy(char* s1,char* s2) { int i=0; while(s2[i]!='0') { s1[i]=s2[i]; i++; } s1[i]='0'; /*string terminates by NULL*/ }
  • 34. C program to concatenate two strings without using library function #include <stdio.h> #include <string.h> #define MAX_SIZE 100 void stringCat (char *s1,char *s2); int main() { char str1[MAX_SIZE],str2[MAX_SIZE]; printf("Enter string 1 : "); scanf("%[^n]s",str1);//read string with spaces getchar();//read enter after entering first string printf("Enter string 2 : "); scanf("%[^n]s",str2);//read string with spaces stringCat(str1,str2); printf("nAfter concatenate strings are :n"); printf("String 1: %s nString 2: %s",str1,str2); printf("n"); return 0; } /*** function definition **/ void stringCat (char *s1,char *s2) { int len,i; len=strlen(s1)+strlen(s2); if(len>MAX_SIZE) { printf("nCan not Concatenate !!!"); return; } len=strlen(s1); for(i=0;i< strlen(s2); i++) { s1[len+i]=s2[i]; } s1[len+i]='0'; /* terminates by NULL*/ }
  • 35. String comparison without using strcmp() function #include <stdio.h> int compare(char[],char[]); int main() { char str1[20]; // declaration of char array char str2[20]; // declaration of char array printf("Enter the first string : "); scanf("%s",str1); printf("Enter the second string : "); scanf("%s",str2); int c= compare(str1,str2); // calling compare() function if(c==0) printf("strings are same"); else printf("strings are not same"); return 0; }
  • 36. // Comparing both the strings. int compare(char a[],char b[]) { int flag=0,i=0; // integer variables declaration while(a[i]!='0' &&b[i]!='0') // while loop { if(a[i]!=b[i]) { flag=1; break; } i++; } if(flag==0) return 0; else return 1; }
  • 37. Given a string and we have to count digits, spaces, special characters and alphabets using C program. #include <stdio.h> int main() { char str[100]; int countDigits, countAlphabet, countSpecialChar, countSpaces; int counter; //assign all counters to zero countDigits = countAlphabet = countSpecialChar = countSpaces = 0; printf("Enter a string: "); gets(str);
  • 38. for (counter = 0; str[counter] != NULL; counter++) { if (str[counter] >= '0' && str[counter] <= '9') countDigits++; else if ((str[counter] >= 'A' && str[counter] <= 'Z') || (str[counter] >= 'a' && str[counter] <= 'z')) countAlphabet++; else if (str[counter] == ' ') countSpaces++; else countSpecialChar++; } printf("nDigits: %d nAlphabets: %d nSpaces: %d nSpecial Characters: %d", countDigits, countAlphabet, countSpaces, countSpecialChar); return 0; }
  • 39. Reverse a string without using library function /*copy characters from last index of str and #include <stdio.h> #include <string.h> int main() { store it from starting in revStr*/ j=0; for(i=(strlen(str)-1); i>=0;i--) revStr[j++]=str[i]; char str[100],revStr[100]; int i,j; printf("Enter a string: "); scanf("%[^n]s",str);//read string with spaces //assign NULL in the revStr revStr[j]='0'; printf("nOriginal String is: %s",str); printf("nReversed String is: %s",revStr); return 0; }
  • 40. Pointer A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is type *var-name; Here, type is the pointer's base type; it must be a valid C data type andvar-nameis the nameof the pointer variable.
  • 41. Pointer The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */
  • 42. Pointer int main () { int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ printf("Address of var variable: %x", ip ); /* access the value using the pointer */ printf("Value of var variable: %d", *ip ); return 0; } Output: Address of var variable: bffd8b3c Value of var variable: 20
  • 43. NULL Pointers It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assignedNULL iscaled anull pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program #include <stdio.h> int main () { int *ptr ; ptr=NULL; printf("The value of ptr is : %xn", ptr ); return 0; }
  • 44. C dereference pointer As we already know that "what is a pointer", a pointer is a variable that stores the address of another variable. The dereference operator is also known as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be returned. Dereference apointer is used becauseof the following reasons: It can be used to access or manipulate the data stored at the memory location, which is pointed by the pointer. Any operation applied to the dereferenced pointer will directly affect the value of the variable that it points to.
  • 45. Using Pointer concept Swap2 values( without usingthird Variable) #include<stdio.h> int main() { int a=10; int b=20; int *p, *q; p=&a; q=&b; *p=*p+*q; *q=*p-*q; *p=*p-*q; printf(after swapping values of a=%d, b=%d, *p, *q); return 0; }
  • 46. Pointer Arithmetic in C with Examples Pointers variables are also known as address data types because they are used to store the address of another variable. The address is the memory location that is assigned to the variable. It doesnt store any value. Hence, there are only a few operations that are allowed to perform on Pointers in C language. The operations are slightly different from the ones that we general y use for mathematical calculations. The operations are: Increment/Decrement of aPointer Addition of integer to apointer Subtractionof integer to apointer Subtractingtwo pointers of the sametype
  • 47. Increment/Decrement of aPointer Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is apointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002. While if a float type pointer is incremented then it will increment by 4(size of afloat) andthe new address will be 1004. Samefor decrement of apointer
  • 48. // C program to illustrate pointer increment/decrement #include <stdio.h> // Driver Code int main() { // Integer variable int N = 4; // Incrementing pointer ptr1; ptr1++; printf("Pointer ptr1 after" " Increment: "); printf("%p nn", ptr1); // Pointer to an integer int *ptr1, *ptr2; printf("Pointer ptr1 before" " Decrement: "); // Pointer stores // the address of N ptr1 = &N; ptr2 = &N; printf("%p n", ptr1); // Decrementing pointer ptr1; ptr1--; Output: printf("Pointer ptr1 " "before Increment: "); printf("%p n", ptr1); } printf("Pointer ptr1 after" " Decrement: "); printf("%p nn", ptr1); return 0; Pointer ptr1 before Increment: 0x7ffcb19385e4 Pointer ptr1 after Increment: 0x7ffcb19385e8 Pointer ptr1 before Decrement: 0x7ffcb19385e8 Pointer ptr1 after Decrement: 0x7ffcb19385e4
  • 49. When a pointer is added with a value, the value is first multiplied by the size of data type and then added to the pointer. // C program to illustrate pointer Addition #include <stdio.h> // Driver Code int main() { // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Addition of 3 to ptr2 ptr2 = ptr2 + 3; printf("Pointer ptr2 after Addition: "); printf("%p n", ptr2); return 0; } Output: // Pointer stores the address of N ptr1 = &N; ptr2 = &N; Pointer ptr2 before Addition: 0x7fffffdcd984 Pointer ptr2 after Addition: 0x7fffffdcd990 printf("Pointer ptr2 before Addition: "); printf("%p n", ptr2);
  • 50. When a pointer is subtracted with a value, the value is first multiplied by the size of the data type and then subtracted from the pointer. // C program to illustrate pointer Subtraction #include <stdio.h> // Driver Code int main() { // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Subtraction of 3 to ptr2 ptr2 = ptr2 - 3; printf("Pointer ptr2 after Subtraction: "); printf("%p n", ptr2); return 0; } Output: Pointer ptr2 before Subtraction: 0x7ffcf1221b24 // Pointer stores the address of N ptr1 = &N; ptr2 = &N; Pointer ptr2 after Subtraction: 0x7ffcf1221b18 printf("Pointer ptr2 before Subtraction: "); printf("%p n", ptr2);
  • 51. Subtraction of Two Pointers The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the increments between the two pointers. For Example: Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are subtracted. The difference between address is 16 bytes. Since the size of int is 2 bytes, therefore the increment between ptr1 and ptr2 is given by (16/2) = 8. Below is the implementation to illustrate the Subtraction of Two Pointers:
  • 52. C program to illustrate Subtraction of two pointers #include <stdio.h> // Driver Code int main() { int x; // Integer variable int N = 4; // Subtraction of ptr2 and ptr1 x = ptr2 - ptr1; // Print x to get the Increment // between ptr1 and ptr2 printf("Subtraction of ptr1 " "& ptr2 is %dn", x); // Pointer to an integer int *ptr1, *ptr2; return 0; } // Pointer stores the address of N ptr1 = &N; ptr2 = &N; Output: Subtraction of ptr1 & ptr2 is 3 // Incrementing ptr2 by 3 ptr2 = ptr2 + 3;
  • 53. Pointers as function arguments Pointer preliminaries: Pointer Definition: A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variableaddress. Function basics: A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additionalfunctions. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides theactual body of the function.
  • 55. Call by value This method copies the actual value of an argument parameter of the function. into the formal In this case, changes made to the parameter inside the function have no effect on the argument. Syntax: Datatype function_name(datatype variable_name);
  • 56. #include <stdio.h> void swap(int i, int j) { int t; t=i; i=j; j=t; } void main() { int a,b; a=5; b=10; printf("%d %dn", a, b); swap(a,b); printf("%d %dn", a, b); }
  • 57. Call by reference: This method copies the address of an parameter. argument into the formal Inside the function, the address is used to argument used in the call. access the actual This means that changes made to the parameter affect the argument. Syntax: datatype function_name(datatype *variable_name);
  • 58. Call by reference Example #include <stdio.h> void swap(int *i, int *j) { int t; t = *i; *i = *j; *j = t; } void main() { int a,b; a=5; b=10; printf("%d %dn",a,b); swap(&a,&b); printf("%d %dn",a,b); }
  • 59. When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of thevalue. So any change made by the function using the pointer is permanently made at the address of passed variable.
  • 60. #include <stdio.h> void salaryhike(int *var, int b) { *var = *var+b; } int main() { int salary=0, bonus=0; printf("Enter the employee current salary:"); scanf("%d", &salary); printf("Enter bonus:"); scanf("%d", &bonus); salaryhike(&salary, bonus); printf("Final salary: %d", salary); return 0; }
  • 61. Example for passing pointers as function argument #include<stdio.h> #include<conio.h> void getDoubleValue(int *F){ *F = *F + 2; printf("F(Formal Parameter) = %dn", *F); } int main(){ int A; printf("Enter a numbersn"); scanf("%d", &A); getDoubleValue(&A); printf("A(ActualParameter) = %dn", A); getch(); }
  • 62. Another Example on passing pointer to function #include <stdio.h> int* larger(int*, int*); void main() { Int a = 15; int b = 92; int *p; p = larger(&a, &b); printf("%d is larger",*p); } int* larger(int *x, int *y) { if(*x > *y) return x; else returny; } OUTPUT: 92 is larger
  • 63. Functions of returning pointers It is also possible for functions to return a function pointer as a value. This ability increases the flexibility of programs. In this case you must be careful, because local variables of function doesn't live outside the function. They have scope only inside the function. Hence if you return a pointer connected to a local variable, that pointer will be pointing to nothing when the function ends
  • 64. Pointer to functions Exampleof function pointers as returnedvalues #include <stdio.h> int* larger(int*, int*); voidmain() { int a = 15; int b = 92; int *p; p = larger(&a, &b); printf("%d is larger",*p); } int* larger(int *x, int *y) { if(*x > *y) return x; else return y; }