0% found this document useful (0 votes)
16 views52 pages

Module 4 Strings Notes Python Vtu

Module-4 covers strings and pointers in C, explaining that strings are arrays of characters terminated by a NULL character. It details string declaration, initialization, reading, and printing methods, including the use of functions like scanf(), gets(), printf(), and puts(). Additionally, it discusses operations on strings, such as finding length and converting to uppercase, along with examples and code snippets.

Uploaded by

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

Module 4 Strings Notes Python Vtu

Module-4 covers strings and pointers in C, explaining that strings are arrays of characters terminated by a NULL character. It details string declaration, initialization, reading, and printing methods, including the use of functions like scanf(), gets(), printf(), and puts(). Additionally, it discusses operations on strings, such as finding length and converting to uppercase, along with examples and code snippets.

Uploaded by

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

Module-4: Strings and Pointers

Strings: Introduction, string taxonomy, operations on strings, Miscellaneous


string and character functions, arrays of strings.

• A string is a array of characters.

• A string can also be defined as sequence of zero or more characters followed by a


NULL character(\0).

Examples:
“HELLO WORLD”

“WELL DONE”

The memory representation of the above can be given as:

Declaration of a string

• There is no separate data type for strings in C.

• They are treated as array of characters.

• They can be declared as:

char s[5];

This string can hold 5 characters including NULL character.

This can be represented as:

s[0] s[1] s[2] s[3] s[4]

Initialization of Array:

char s[5]={‘r’, ‘a’, ‘m’, ‘a’};

Nisha S K, Dept. of ECE, SVIT Page 1


Module-4: Strings and Pointers

char s[5]=“rama”;

Reading and Printing string:

The strings can be read from keyboard and can be displayed in 2 ways.

I/O
Functions

Formatted Unformatted

printf(output) scanf(input) puts(output) gets(input)

Reading Strings
o If we declare a string by writing
char str[100];
o We can read the string ‘str’ by using 3 ways, namely:
1. using scanf() function
2. using gets() function
3. using getchar(), getch() and getche() function repeatedly

1. Using scanf() function:


 We can use the scanf() function to read a string.
 The scanf() function reads the sequence of characters until it encounters the first
whitespace character(space, newline, tab, etc.).
 It terminates reading further and appends a null character to the string that has
been read
 Syntax:
scanf(“%s”,str);
 Example: C program to scan a string variable using scanf()
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");

Nisha S K, Dept. of ECE, SVIT Page 2


Module-4: Strings and Pointers

scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

OUTPUT:
Enter name: Dennis Ritchie
Your name is Dennis

 Even though Dennis Ritchie was entered in the above program, only "Dennis" was
stored in the name string. It's because there was a space after Dennis.
 Also notice that we have used the code name instead of &name with scanf().
 This is because name is a char array, and we know that array names decay to
pointers in C.
 Thus, the name in scanf() already points to the address of the first element in the
string, which is why we don't need to use &.

2. Using gets() function:


 Reads characters from the standard input (stdin) and stores them as a C string
into the string variable ‘str’ until a newline character or the end-of-file is reached.
 All the characters entered by the user get stored in a character array. The null
character is added to the array to make it a string.
 The gets() allows the user to enter the space-separated strings. It returns the
string entered by the user.
 It is not safe to use because it does not check the array bound.
 It is used to read strings from the user until a newline character is not
encountered.
 Example:
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string:\n ");
gets(s);
printf("You entered: \n%s",s);
}
Output:
Enter the string:
Programming is the best

Nisha S K, Dept. of ECE, SVIT Page 3


Module-4: Strings and Pointers

You entered:
Programming is the best

 Difference between scanf() and gets() :

scanf() gets()
when scanf() is used to when gets() is used to read input it
read string input it stops stops reading input when it
reading when it encounters encounters newline or End Of File. It
whitespace, newline or End does not stop reading the input on
Of File encountering whitespace as it
considers whitespace as a string.
It is used to read input of It is used only for string input.
any datatype
Its syntax is -: Its syntax is -:

scanf(const char *format, char *gets(char *str)


…)
It is fast to take input. It takes one parameter that is the
pointer to an array of chars
Format specifiers is used Its return value is str on success else
inside scanf to take input. NULL.

3. Using getchar() function:


 C getchar is a standard library function that takes a single input character from
standard input
 It is defined inside the <stdio.h> header file.
 Syntax of getchar() in C
getchar(void);
 getchar() function does not take any parameters.
Return Value
The input from the standard input is read as an unsigned char and then it is
typecast and returned as an integer value(int).
 EOF is returned in two cases:
o When the file end is reached
o When there is an error during the execution
 Example:
int main()
{
char character;

Nisha S K, Dept. of ECE, SVIT Page 4


Module-4: Strings and Pointers

printf(“Enter the character\n”);


character = getchar();

printf("The entered character is :\n %c", character);


return 0;
}
Output:
Enter the character
g
The entered character is :
g

Writing Strings
 Strings can be displayed on monitor screen using three ways:
1. Using printf() function
2. Using puts() function
3. Using putchar() function repeatedly

1. Using printf() function


 We can use the printf() function to display/print a string to the monitor screen.
 The printf() function prints the string from first character to the last character
until it encounters a null character.
 Syntax:
printf(“%s”,str);
 Example: C program to scan a string variable using scanf()

#include <stdio.h>
int main()
{
char name[20] = “Programming is Fun”;
printf("String content is \n%s.", name);
return 0;
}
Output:
String content is
Programming is Fun
 The conversion character ‘s’ is used to print the string in the format specifier “%s”

Nisha S K, Dept. of ECE, SVIT Page 5


Module-4: Strings and Pointers

 The width and precision specifications also could be used along with format
specifier
o The width specifies the total number of characters to be displayed. If the string is
short, extra space is left padded or right padded
o A negative width justifies the string to the left rather its usual right justification
o The Precision specifies the maximum number of characters to be displayed.
o If the string is long, the extra characters are truncated
o If the field width is less than the length of the string, the entire string will be
printed
o If the precision is zero, then nothing is printed on the string
 Example
#include <stdio.h>
int main()
{
char str[10] = "COMPUTER";
printf("|%s|\n",str);
printf("|%20s|\n",str);
printf("|%20.4s|\n",str);
printf("|%-20.4s|\n",str);
printf("|%5s|\n",str);
printf("|%20.0s|\n",str);
printf("|%*.*s|\n",10,5,str);
}
Output:
|COMPUTER|
| COMPUTER|
| COMP|
|COMP |
|COMPUTER|
| |
| COMPU|

2. Using puts() function


 puts() is a function defined in header <stdio.h> that prints strings character by
character until the NULL character is encountered
 The puts() function prints the newline character at the end of the output string.
 Syntax
puts(str);
where, str: string to be printed.

Nisha S K, Dept. of ECE, SVIT Page 6


Module-4: Strings and Pointers

 Return Value
The return value of the puts function depends on the success/failure of its execution.
o On success, the puts() function returns a non-negative value.
o Otherwise, an End-Of-File (EOF) error is returned.
 Example:

#include <stdio.h>
int main()
{
// using puts to print hello world
char str = "Programming in C";
puts(str);
puts("Programming is Fun");
return 0;
}
Output:
Programming in C
Programming is Fun

3. Using putchar() function


 The putchar(int ch) method in C is used to write a character, of unsigned char
type, to monitor screen. This character is passed as the parameter to this method.
 Syntax:
putchar(ch);
 Parameters:
This method accepts a mandatory parameter ch which is the character to be written
to stdout.
 Return Value:
This function returns the character written on the screen as an unsigned char. It also
returns EOF when some error occurs.
 Since the putchar() is capable of printing only one character to the screen, the
function needs to be repeatedly called to print the entire string.
 Example:

#include <stdio.h>
int main()
{
// using putchar to print Computer Device
char str = "Computer Device";
int i=0;

Nisha S K, Dept. of ECE, SVIT Page 7


Module-4: Strings and Pointers

while(str[i]!=’\0’)
{
putchar(str[i]);
i++;
}
return 0;
}
Output:
Computer Device

Suppressing Input
 The scanf() is used to read a data without assigning it to any variable.
 This is done by preceeding that field’s format code with a ‘*’
 The * is a suppressing character which tells scanf to consume the input but not
try to assign it to a variable and the c conversion specifier asks to read any character
 Example:

#include <stdio.h>
int main()
{
scanf(“%d*c%d”,&hr,&min);
scanf("%s %*c %s",s1,s2);
printf("%s %s\n",s1,s2);
scanf("%d %*c %d",&hr,&min);
printf("%d %d\n",hr,min);
}
Output:
Hello - Everyone
Hello Everyone
10 : 45
10 45
 The string can be read as Hello - Everyone, here ‘-‘ the, would be read but not
assigned to anything
 Thus, assignment suppression is helpful when part of what input needs to be
suppressed

Nisha S K, Dept. of ECE, SVIT Page 8


Module-4: Strings and Pointers

Using a Scanset

 scanf family functions support scanset specifiers which are represented by %[].
Inside scanset, we can specify single character or range of characters. While
processing scanset, scanf will process only those characters which are part of scanset
 We can define scanset by putting characters inside square brackets. Please note
that the scansets are case-sensitive.
 Example:
scanf(%[A-Z_abc]s,str);
This will scan all the specified character in the scanset i.e., All capital letters, an
underscore and only lowercase a,b,c alphabets and stops reading the string on
encountering the first non scanset character from keyboard
 If first character of scanset is ‘^’, then the specifier will stop reading after first
occurrence of that character. For example, given below scanset will read all
characters but stops after first occurrence of the character ‘9’
 Example
scanf(%[^9]s,str);
 C program to demonstrate scanset in scanf() function
#include <stdio.h>
int main(void)
{
char str[128],str2[20];
printf("Enter a string with : ");
scanf("%[ A-za-z0-9!@#]s", str1);
printf("You entered: %s\n", str);
printf("You entered: %s\n", str1);
printf("Enter a string without vowels: ");
scanf("%[^aeiou]s", str2);
printf("You entered: %s\n", str);
return 0;
}
Output:
Enter a string : Hello Everyone 123@#$%^&*ju
You entered: Hello Everyone 123@#
Enter a string without vowels : qwerty keyboard
You entered: qw

Nisha S K, Dept. of ECE, SVIT Page 9


Module-4: Strings and Pointers

sprintf and sscanf:

sprintf: It stands for "string print formatted." It is used to write formatted data to a
string.

Example:

#include <stdio.h>

int main() {

char buffer[50];

int num = 42;

float fnum = 3.14;

// Format the data into a string

sprintf(buffer, "The number is %d and the float is %.2f", num, fnum);

// Print the formatted string

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

return 0;

sscanf: It stands for "string scan formatted." It is used to read data from a string into
variables, using a format specifier.

#include <stdio.h>

int main() {

char data[] = "The number is 42 and the float is 3.14";

int num;

float fnum;

// Extract data from the string

sscanf(data, "The number is %d and the float is %f", &num, &fnum);

// Print the extracted values

Nisha S K, Dept. of ECE, SVIT Page 10


Module-4: Strings and Pointers

printf("Extracted values: %d, %.2f\n", num, fnum);

return 0;

In this example, sscanf reads the values of num and fnum from the string data using
the specified format, and then we print the extracted values.

In this example, sprintf formats the integer num and float fnum into the string
buffer, and then we print the contents of buffer which will be "The number is 42 and
the float is 3.14".

Operations on strings:

1. Finding the length of a string:

ALGORITHM TO CALCULATE THE LENGTH OF A STRING

Step 1: [INITIALIZE] SET I = 0

Step 2: Repeat Step 3 while STR[I] != '\0'

Step 3: SET I = I + 1

[END OF LOOP]

Step 4: SET LENGTH = I

Step 5: END

Program:

#include <stdio.h>

int main()

char a[20],i=0,len;

printf("Enter the string: ");

gets(a);

while(a[i]!='\0')

Nisha S K, Dept. of ECE, SVIT Page 11


Module-4: Strings and Pointers

i++;

len=i;

printf("The length of the string is %d",len);

Output:

Enter the string: CLASS

The length of the string is 5

2. Converting Characters of a string into Upper case:

ALGORITHM TO CONVERT THE CHARACTERS OF STRING INTO UPPER CASE

Step1: [Initialize] SET I=0

Step 2: Repeat Step 3 while STR[I] != ‘\0’

Step 3: IF STR[1] >= ‘a’ AND STR[I] <= ‘z’

SET Upperstr[I] = STR[I] - 32

ELSE

SET Upperstr[I] = STR[I]

[END OF IF]

SET I=I+1

[END OF LOOP]

Step 4: SET Upperstr[I] = ‘\0’

Step 5: EXIT

Program:

#include <stdio.h>

int main()

Nisha S K, Dept. of ECE, SVIT Page 12


Module-4: Strings and Pointers

char a[20],uprstr[20];

int i=0,j=0;

printf("Enter the string: ");

gets(a);

while(a[i]!='\0')

if(a[i]>='a'&&a[i]<='z')

uprstr[j]=a[i]-32;

else

uprstr[j]=a[i];

i++;

j++;

uprstr[j]='\0';

printf("The string in upper case is ");

puts(uprstr);

Output:

Enter the string: class

The string in upper case is CLASS

3. Converting Characters of a string into Lower case:

ALGORITHM TO CONVERT THE CHARACTERS OF STRING INTO LOWER CASE

Step1: [Initialize] SET I=0

Step 2: Repeat Step 3 while STR[I] != ‘\0’

Nisha S K, Dept. of ECE, SVIT Page 13


Module-4: Strings and Pointers

Step 3: IF STR[1] >= ‘A’ AND STR[I] <= ‘Z’

SET Lowerstr[I] = STR[I] + 32

ELSE

SET Lowerstr[I] = STR[I]

[END OF IF]

SET I=I+1

[END OF LOOP]

Step 4: SET Lowerstr[I] = ‘\0’

Step 5: EXIT

Program:

#include <stdio.h>

int main()

char a[20],lwrstr[20];

int i=0,j=0;

printf("Enter the string: ");

gets(a);

while(a[i]!='\0')

if(a[i]>='A'&&a[i]<='Z')

lwrstr[j]=a[i]+32;

else

lwrstr[j]=a[i];

i++;

Nisha S K, Dept. of ECE, SVIT Page 14


Module-4: Strings and Pointers

j++;

lwrstr[j]='\0';

printf("The string in lower case is ");

puts(lwrstr);

Output:

Enter the string: CLASS

The string in lower case is class

4. Concatenating two strings to form a New string:

ALGORITHM TO CONCATENATE TWO STRINGS

Step 1: Initialize I =0 and J=0

Step 2: Repeat step 3 to 4 while str1[I] != NULL

Step 3: SET new_str[J] = str1[I]

Step 4: Set I =I+1 and J=J+1

[END of loop]

Step 5: SET I=0

Step 6: Repeat step 4 to 5 while str2[I] != NULL

Step 7: SET new_str[J] = str2[I]

Set I =I+1 and J=J+1

[END of loop]

Step 5: SET new_str[J] = ‘\0’

Step 6: EXIT

Nisha S K, Dept. of ECE, SVIT Page 15


Module-4: Strings and Pointers

Program:

#include<stdio.h>

void main()

char a[20]="Hi,",b[20]="Nisha",c[20];

int i=0,j=0;

while(a[i]!='\0')

c[j]=a[i];

i++;

j++;

i=0;

while(b[i]!='\0')

c[j]=b[i];

i++;

j++;

c[j]='\0';

printf("The concatenated string is:");

puts(c);

Nisha S K, Dept. of ECE, SVIT Page 16


Module-4: Strings and Pointers

Output:

The concatenated string is:Hi,Nisha

5. Appending a string to another string:

• Appending one string to another string involves copying the contents of the
source string at the end of the destination string.

• For example, if S1 and S2 are two strings, then appending S1 to S2 means


we have to add the contents of S1 to S2. so S1 is the source string and S2 is the
destination string.

• The appending operation would leave the source string S1 unchanged and
destination string S2 = S2+S1.

ALGORITHM TO APPEND A STRING TO ANOTHER STRING

Step 1: [Initialize] SET I =0 and J=0

Step 2: Repeat Step 3 while Dest_Str[I] != ‘\0’

Step 3: SET I = I + 1

[END OF LOOP]

Step 4: Repeat Step 5 to 7 while Source_Str[J] != ‘\0’

Step 5: Dest_Str[I] = Source_Str[J]

Step 6: SET I = I + 1

Step 7: SET J = J + 1

[END OF LOOP]

Step 8: SET Dest_Str[J] = ‘\0’

Step 9: EXIT

Program:

#include<stdio.h>

void main()

Nisha S K, Dept. of ECE, SVIT Page 17


Module-4: Strings and Pointers

char dest[100],src[100];

int i=0,j=0;

printf("Enter source str: ");

gets(src);

printf("Enter dest str: ");

gets(dest);

while(dest[i]!='\0')

i++;

while(src[j]!='\0')

dest[i]=src[j];

i++;

j++;

dest[i]='\0';

printf("After appending, the destination is: ");

puts(dest);

Output:

Enter source str: Room

Enter dest str: Class

After appending, the destination is: ClassRoom

6. Comparing 2 strings:

If S1 and S2 are two strings then comparing two strings will give either of these
results-

Nisha S K, Dept. of ECE, SVIT Page 18


Module-4: Strings and Pointers

• S1 and S2 are equal

• S1>S2, when in dictionary order S1 will come after S2

• S1<S2, when in dictionary order S1 precedes S2

Algorithm:

Step 1: [Initialize] SET I=0, SAME =0

Step 2: SET Len1 = Length(STR1), Len2 = Length(STR2)

Step 3: IF len1 != len2, then

Write “Strings Are Not Equal”

ELSE

Repeat while I<Len1

IF STR1[I] == STR2[I]

SET I = I + 1

ELSE

Go to Step 4

[END OF IF]

[END OF LOOP]

IF I = Len1, then

SET SAME =1

Write “Strings are equal”

[END OF IF]

Step 4: IF SAME = 0, then

IF STR1[I] > STR2[I], then

Write “String1 is greater than String2”

ELSE IF STR1[I] < STR2[I], then

Nisha S K, Dept. of ECE, SVIT Page 19


Module-4: Strings and Pointers

Write “String2 is greater than String1”

[END OF IF]

[END OF IF]

Step 5: EXIT

Program:

#include<stdio.h>

#include<string.h>

void main()

char a[100],b[100];

int i=0,len1=0,len2=0,same=0;

printf("Enter first str: ");

gets(a);

printf("Enter second str: ");

gets(b);

len1=strlen(a);

len2=strlen(b);

if(len1==len2)

while(i<len1)

if(a[i]==b[i])

i++;

else

Nisha S K, Dept. of ECE, SVIT Page 20


Module-4: Strings and Pointers

break;

if(i==len1)

same=1;

printf("The two strings are equal");

if(len1!=len2)

printf("The 2 strings are not equal\n");

if(same==0)

if(a[i]>b[i])

printf("String 1 is greater than String 2");

else if(a[i]<b[i])

printf("String 2 is greater than String 1");

Output:

Enter first str: Class

Enter second str: Class

The two strings are equal

7. Reversing a string:

• If S1= “HELLO”, then reverse of S1 = “OLLEH”.

Nisha S K, Dept. of ECE, SVIT Page 21


Module-4: Strings and Pointers

• To reverse a string we just need to swap the first character with the last, second
character with the second last character, so on and so forth.

ALGORITHM TO REVERSE A STRING

Step 1: [Initialize] SET I=0, J= Length(STR)-1

Step 2: Repeat Step 3 and 4 while I< J

Step 3: SWAP( STR(I), STR(J))

Step 4: SET I = I + 1, J = J – 1

[END OF LOOP]

Step 5: EXIT

Program:

#include <stdio.h>

#include <string.h>

int main ()

char a[100],temp;

int i=0,j=0;

printf("Enter the string: ");

gets(a);

j=strlen(a)-1;

while(i<j)

temp=a[j];

a[j]=a[i];

a[i]=temp;

i++;

Nisha S K, Dept. of ECE, SVIT Page 22


Module-4: Strings and Pointers

j--;

printf("The reversed string is: ");

puts(a);

Output:

Enter the string: HELLO

The reversed string is: OLLEH

8. Extracting a substring from left:

• In order to extract a substring from the main string we need to copy the content of
the string starting from the first position to the nth position where n is the number of
characters to be extracted.

• For example, if S1 = “Hello World”, then Substr_Left(S1, 7) = Hello W

ALGORITHM TO EXTRACT N CHARCTERS FROM RIGHT OF A STRING

Step 1: [Initialize] SET I=0

Step 2: Repeat Step 3 to 4 while STR[I] != ‘\0’ AND I<N

Step 3: SET Substr[I] = STR[I]

Step 4: SET I = I + 1

[END OF LOOP]

Step 5: SET Substr[I] =’\0’

Step 6: EXIT

Program:

#include <stdio.h>

#include <string.h>

int main ()

Nisha S K, Dept. of ECE, SVIT Page 23


Module-4: Strings and Pointers

char a[100],substr[100];

int i=0,n;

printf("Enter the string: ");

gets(a);

printf("Enter the number of characters to be copied: ");

scanf("%d",&n);

i=0;

while(a[i]!='\0'&&i<n)

substr[i]=a[i];

i++;

substr[i]='\0';

printf("The substring is: ");

puts(substr);

Output:

Enter the string: Classroom

Enter the number of characters to be copied: 5

The substring is: Class

9. Extracting a substring from right:

• In order to extract a substring from the right side of the main string we need to
first calculate the position. For example, if S1 = “Hello World” and we have to copy 7
characters starting from the right, then we have to actually start extracting

Nisha S K, Dept. of ECE, SVIT Page 24


Module-4: Strings and Pointers

characters from the 5th position. This is calculated by, total number of characters – n
+ 1.

• For example, if S1 = “Hello World”, then Substr_Right(S1, 7) =o World

ALGORITHM TO EXTRACT N CHARCTERS FROM RIGHT OF A STRING

Step 1: [Initialize] SET I=0, J = Length(STR) – N

Step 2: Repeat Step 3 to 4 while STR[J] != ‘\0’

Step 3: SET Substr[I] = STR[J]

Step 4: SET I = I + 1, J = J + 1

[END OF LOOP]

Step 5: SET Substr[I] =’\0’

Step 6: EXIT

Program:

#include <stdio.h>

#include <string.h>

int main ()

char a[100],substr[100];

int i=0,j=0,n;

printf("Enter the string: ");

gets(a);

printf("Enter the number of characters to be copied: ");

scanf("%d",&n);

j=strlen(a)-n;

while(a[j]!='\0')

Nisha S K, Dept. of ECE, SVIT Page 25


Module-4: Strings and Pointers

substr[i]=a[j];

i++;

j++;

substr[i]='\0';

printf("The substring is: ");

puts(substr);

Output:

Enter the string: Classroom

Enter the number of characters to be copied: 4

The substring is: room

10. Extracting a substring from middle of a string:

• To extract a substring from a given string requires information about three things

1. the main string

2. the position of the first character of the substring in the given string

3. maximum number of characters/length of the substring

For example, if we have a string-

str[] = “Welcome to the world of programming”; then,

SUBSTRING(str,15,5) = world

Algorithm to extract substring from a given text

Step 1: [INITIALIZE] Set I=M, J = 0

Step 2: Repeat steps 3 to 6 while str[I] != ‘0’ and N>0

Step 3: SET substr[J] = str[I]

Nisha S K, Dept. of ECE, SVIT Page 26


Module-4: Strings and Pointers

Step 4: SET I = I + 1

Step 5: SET J = J + 1

Step 6: SET N = N – 1

[END of loop]

Step 7: SET substr[J] = ‘\0’

Step 8: EXIT

Program:

#include <stdio.h>

#include <string.h>

int main ()

char a[100],substr[100];

int i=0,j=0,n,m;

printf("Enter the main string: ");

gets(a);

printf("Enter the position from which to start the substring: ");

scanf("%d",&m);

printf("Enter the length of the string: ");

scanf("%d",&n);

i=m;

while(a[i]!='\0'&&n>0)

substr[j]=a[i];

i++; j++;n--;

Nisha S K, Dept. of ECE, SVIT Page 27


Module-4: Strings and Pointers

substr[j]='\0';

printf("The substring is: ");

puts(substr);

Output:

Enter the main string: Classroom

Enter the position from which to start the substring: 5

Enter the length of the string: 4

The substring is: room

11. Inserting a string into another string:

• The insertion operation inserts a string S in the main text, T at the kth position.

• The general syntax of this operation is:

• INSERT(text, position, string).

• For ex, INSERT(“XYZXYZ”, 3, “AAA”) = “XYZAAAXYZ”

Algorithm to insert a string in the main text

Step 1: [INITIALIZE] SET I=0, J=0 and K=0

Step 2: Repeat steps 3 to 4 while text[I] != ‘0’

Step 3: IF I = pos, then

Repeat while str[K] != ‘\0’

new_str[j] = str[k]

SET J=J+1

SET K = K+1

[END OF INNER LOOP]

Nisha S K, Dept. of ECE, SVIT Page 28


Module-4: Strings and Pointers

ELSE

new_str[[J] = text[I]

SET J = J+1

Step 4: SET I = I+1

[END OF OUTER LOOP]

Step 5: SET new_str[J] = ‘\0’

Step 6: EXIT

Program:

#include <stdio.h>

#include<string.h>

int main()

char str[100],subStr[50],newStr[100];

int n,i,j,k;

printf("Enter a string: \n");

scanf("%s",str);

printf("Enter the substring to insert\n");

scanf("%s",subStr);

printf("Enter the location to insert the sub string:\n");

scanf("%d",&n);

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

for(i=0;i<strlen(str)-n;i++)

newStr[i] = str[i];

Nisha S K, Dept. of ECE, SVIT Page 29


Module-4: Strings and Pointers

for(k=n,j=0;subStr[j]!='\0';k++)

newStr[k]=subStr[j++];

for(i=i;str[i]!='\0';i++)

newStr[k++] = str[i];

newStr[k]='\0';

printf("String after inserting substring is:\n %s\n",newStr);

return 0;

Output:

Enter a string:

Pram

Enter the substring to insert

ogr

Enter the location to insert the sub string:

String is: Pram

String after inserting substring is:

Program

Nisha S K, Dept. of ECE, SVIT Page 30


Module-4: Strings and Pointers

12. Indexing:

Algorithm to find the index of the first occurrence of a string within a given
text

Step 1: [Initialize] SET I=0 and MAX = LENGTH(text) – LENGTH(str) +1

Step 2: Repeat Steps 3 to 6 while I <= MAX

Step 3: Repeat step 4 for K = 0 To Length(str)

Step 4: IF str[K] != text[I + K], then GOTO step 6

[END of inner loop]

Step 5: SET INDEX = I. Goto step 8

Step 6: SET I = I+1

[END OF OUTER LOOP]

Step 7: SET INDEX = -1

Step 8: EXIT

13. Deleting a Substring from the main string:

Algorithm to delete a substring from a text

Step 1: [INITIALIZE] SET I=0 and J=0

Step 2: Repeat steps 3 to 6 while text[I] !=’\0’

Step 3: IF I=M, then

Repeat Step 4 while N>=0

SET I = I+1

SET N = N – 1

[END of inner loop]

[END OF IF]

Step 4: SET new_str[J] = text[I]

Step 5: SET J= J + 1

Nisha S K, Dept. of ECE, SVIT Page 31


Module-4: Strings and Pointers

Step 6: SET I = I + 1

[ END of outer loop]

Step 7: SET new_str[J] = ‘\0’

Step 8: EXIT

Program:

#include <stdio.h>

#include <string.h>

int main ()

char a[100],b[100],c[100];

int i=0,j=0,k,n=0,loop=0;

printf("Enter the main string: ");

gets(a);

printf("Enter the string to be deleted: ");

gets(b);

while(a[i]!='\0')

j=0,k=i;

while(a[k]==b[j]&&b[j]!='\0')

k++;

j++;

if(b[j]=='\0')

Nisha S K, Dept. of ECE, SVIT Page 32


Module-4: Strings and Pointers

loop=k;

c[n]=a[loop];

i++;

loop++;

n++;

c[n]='\0';

printf("The substring is: ");

puts(c);

Output:

Enter the main string: Classroom

Enter the string to be deleted: room

The substring is: Class

Miscellaneous string and character functions

Miscellaneous character functions

S.No Function Description Return Values


1. isalnum() This function Returns 0 if the passed argument is
identifies the non – alphanumeric character
alphanumeric Returns non zero value if the passed
characters argument is alphanumeric character
2. isalpha() This function Returns 0 if the passed argument is not
identifies the an alphabet
alphabets from Returns non zero value if the passed
other characters argument is an alphabet
3. isblank() This function Returns 0 if the passed argument is not
identifies the a blank space
blank spaces from Returns nonzero value if the passed
other characters argument is a blank space

Nisha S K, Dept. of ECE, SVIT Page 33


Module-4: Strings and Pointers

4. iscntrl() This function Returns 0 if the passed argument is not


identifies the a control character
control Returns nonzero value if the passed
characters(\n, \b, argument is a control character
\t, \r).
5. isdigit() This function Returns 0 if the passed argument is not
identifies numbers a number
in character. Returns nonzero value if the passed
argument is a number
6. islower() This function Returns 0 if the passed argument is not
identifies the a lowercase alphabet
lowercase Returns nonzero value if the passed
alphabets. argument is a lowercase alphabet
7. isprint() This function Returns 0 if the passed argument is a
identifies the non printable character
printable Returns nonzero value if the passed
characters. argument is a printable character
8. ispunct() This function Returns 0 if the passed argument is not
identifies a punctuation character
punctuation Returns nonzero value if the passed
characters argument is a punctuation character
(characters that
are neither
alphanumeric nor
space).
9. isspace() This function Returns 0 if the passed argument is not
identifies white- a white-space character
space characters. Returns nonzero value if the passed
argument is a white-space character
10. isupper() This function Returns 0 if the passed argument is not
identifies the an uppercase alphabet
uppercase Returns nonzero value if the passed
alphabets. argument is an uppercase alphabet
11. isxdigit() This function Returns 0 if the passed argument is not
identifies the a hexadecimal digit
hexadecimal digit. Returns nonzero value if the passed
argument is an hexadecimal digit
12. tolower() This function Returns lowercase alphabet of the
converts corresponding uppercase alphabet

Nisha S K, Dept. of ECE, SVIT Page 34


Module-4: Strings and Pointers

uppercase
alphabet to
lowercase
alphabet.
13. toupper() This function Returns uppercase alphabet of the
converts lowercase corresponding lowercase alphabet
alphabet to
uppercase
alphabet.

String manipulation functions

1. strlen(str): This function returns the length of the string.

Example:

#include<stdio.h>

#include<string.h>

void main()

char a[10];

int l;

printf("Enter a string: ");

scanf("%s",a);

l=strlen(a);

printf("\nLength of the string is %d",l);

Output:

Enter a string: CLASS

Length of the string is 5

Nisha S K, Dept. of ECE, SVIT Page 35


Module-4: Strings and Pointers

2. strcpy(dest str,src str): This function copies source string to destination string.

Example:

#include<stdio.h>

#include<string.h>

void main()

char a[10],b[10];

printf("Enter a string: ");

scanf("%s",a);

strcpy(b,a);

printf("\nValue of a: %s",a);

printf("\nValue of b: %s",b);

Output:

Enter a string: Classroom

Value of a: Classroom

Value of b: Classroom

3. strncpy(dest,src,length): This function copies source string to destination string


ut only upto specified length.

Example:

#include<stdio.h>

#include<string.h>

void main()

char a[10],b[10];

Nisha S K, Dept. of ECE, SVIT Page 36


Module-4: Strings and Pointers

printf("Enter a string: ");

scanf("%s",a);

strncpy(b,a,3);

printf("\nValue of a: %s",a);

printf("\nValue of b: %s",b);

Output:

Enter a string: Classroom

Value of a: Classroom

Value of b: Cla

4. strcmp(string1,string2): This function is used to compare two strings. They are


case sensitive.

Example:

#include<stdio.h>

#include<string.h>

void main()

char a[30],b[30];

int n;

printf("Enter string 1: ");

scanf("%s",a);

printf("Enter string 2: ");

scanf("%s",b);

n=strcmp(a,b);

if(n==0)

Nisha S K, Dept. of ECE, SVIT Page 37


Module-4: Strings and Pointers

printf("Both the strings are equal");

else

printf("Both the strings are not equal");

Output 1:

Enter string 1: Class

Enter string 2: Room

Both the strings are not equal

Output 2:

Enter string 1: Class

Enter string 2: Class

Both the strings are equal

5. strncmp(string1,string2,length): This function is used to compare two strings


upto a specified length. They are case sensitive.

#include<stdio.h>

#include<string.h>

void main()

char a[30],b[30];

int n;

printf("Enter string 1: ");

Nisha S K, Dept. of ECE, SVIT Page 38


Module-4: Strings and Pointers

scanf("%s",a);

printf("Enter string 2: ");

scanf("%s",b);

n=strncmp(a,b,3);

if(n==0)

printf("Both the strings are equal upto first 3 strings");

else

printf("Both the strings are not equal");

Output:

Enter string 1: Class

Enter string 2: Classroom

Both the strings are equal upto first 3 strings

6. strcat(string1,string2): This function is used to concatenate 2 strings.

#include<stdio.h>

#include<string.h>

void main()

char a[30],b[30];

printf("Enter string 1: ");

Nisha S K, Dept. of ECE, SVIT Page 39


Module-4: Strings and Pointers

scanf("%s",a);

printf("Enter string 2: ");

scanf("%s",b);

strcat(a,b);

printf("Final string is %s",a);

Output:

Enter string 1: Class

Enter string 2: Room

Final string is ClassRoom

7. strncat(string1,string2,length): This function is used to concatenate 2 strings


upto specified length.

#include<stdio.h>

#include<string.h>

void main()

char a[30],b[30];

printf("Enter string 1: ");

scanf("%s",a);

printf("Enter string 2: ");

scanf("%s",b);

strncat(a,b,3);

printf("Final string is %s",a);

Output:

Nisha S K, Dept. of ECE, SVIT Page 40


Module-4: Strings and Pointers

Enter string 1: Class

Enter string 2: Room

Final string is ClassRoo

8. strchr(string,character to find): This function searches for the first occurrence of


the character in the string pointed to.

#include <stdio.h>

#include <string.h>

int main ()

const char str[] = "This is just a String";

const char ch = 'u';

char *p;

p = strchr(str, ch);

printf("String starting from %c is: %s", ch, p);

return 0;

Output:

String starting from u is: ust a String

9. strrchr(string,character to find): This function searches for the first occurrence


of the character beginning at the rear end and working towards the front.

#include <stdio.h>

#include <string.h>

int main ()

const char str[] = "This-is-just-a-test-string";

Nisha S K, Dept. of ECE, SVIT Page 41


Module-4: Strings and Pointers

const char ch = '-';

char *p, *p2;

p = strrchr(str, ch);

printf("String starting from last occurrence of %c is: %s\n", ch, p);

p2 = strrchr(str, 'i');

printf("String starting from last occurrence of 'i' is: %s\n", p2);

return 0;

Output:

String starting from last occurrence of - is: -string

String starting from last occurrence of 'i' is: ing

9. strstr(string1,string2): This function is used to find the occurrence of string 2 in


the string 1.

#include <stdio.h>

#include <string.h>

int main () {

const char str[20] = "Hello, how are you?";

const char searchString[10] = "you";

char *result;

result = strstr(str, searchString);

printf("The substring starting from the given string: %s", result);

return 0;

Output:

The substring starting from the given string: you?

Nisha S K, Dept. of ECE, SVIT Page 42


Module-4: Strings and Pointers

10. strspn(string1,string2): This function returns the index of first character in


string1 that does not match any character in string2.

#include <stdio.h>

#include <string.h>

void main ()

int len;

char str1[100];

char str2[100];

printf("Enter str1:");

gets(str1);

printf("Enter str2:");

gets(str2);

len = strspn(str1,str2);

printf("Number of matched characters: %d\n",len);

Output:

Enter str1:Class

Enter str2:Class

Number of matched characters: 5

11. strcspn(string1,string2): This function returns the index of first character in


string1 that matches any character in string2.

#include <stdio.h>

#include <string.h>

void main ()

Nisha S K, Dept. of ECE, SVIT Page 43


Module-4: Strings and Pointers

int len;

char str1[100];

char str2[100];

printf("Enter str1:");

gets(str1);

printf("Enter str2:");

gets(str2);

len = strcspn(str1,str2);

printf("The unmatched characters before first matched character : %d\n",len);

Output:

Enter str1:Class

Enter str2:Room

The unmatched characters before first matched character : 5

12. strpbrk(string1,string2): This function returns a pointer to the first occurrence


in str1 of any character in str2, or NULL if none are present.

#include <stdio.h>

#include <string.h>

int main ()

const char s1[] = "Helloworld";

const char s2[] = "Blank";

char *result;

result = strpbrk(s1, s2);

Nisha S K, Dept. of ECE, SVIT Page 44


Module-4: Strings and Pointers

printf("The matching character : %c", *result);

return(0);

Output:

The matching character : l

13. strtok(string1,delimiter): This function is used to isolate sequential tokens in a


null-terminated string.

#include <string.h>

#include <stdio.h>

int main()

char s[16] = "A,B,C,D";

char* tok = strtok(s, ",");

while (tok != NULL)

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

tok = strtok(NULL, ",");

return 0;

Output:

Nisha S K, Dept. of ECE, SVIT Page 45


Module-4: Strings and Pointers

Arrays of Strings:

An array of string is declared as,

char array_name[row_size][col_size];

If we have an array declared as,

char name[5][10] = {“Ram”, “Mohan”, “Shyam”, “Hari”, “Gopal”};

Row 1

Row 2

Row 3

Row 4

Row 5

#include<stdio.h>

void main()

char names[5][10];

int i,n;

printf("\n Enter the number of students : ");

scanf("%d",&n);

for(i=0;i<n;i++)

printf("\nEnter the name of the students %d: ",i+1);

scanf("%s",names[i]);

Nisha S K, Dept. of ECE, SVIT Page 46


Module-4: Strings and Pointers

printf("\n Names of the students are : \n");

for(i=0;i<n;i++)

puts(names[i]);

Output:

Enter the number of students : 2

Enter the name of the students 1: Nisha

Enter the name of the students 2: Isha

Names of the students are :

Nisha

Isha

Write functions to implement string operations such as compare, concatenate,


and find string length. Use the parameter passing techniques.

#include <stdio.h>

int main ()

char string1[20], string2[20]; //string variables declaration with size 20

int choice;

printf("\n1.Find Length\n2.Concatenate\n3.Compare\n4.Exit\n");

printf("\nEnter your choice: \t ");

scanf("%d", & choice);

switch (choice)

case 1:

printf("\nEnter the string: \t");

Nisha S K, Dept. of ECE, SVIT Page 47


Module-4: Strings and Pointers

scanf("%s", string1);

printf("\n\nThe length of string is %d\n\n", find_length(string1));

break;

case 2:

printf("\n\nEnter two strings: \t");

scanf("%s \n %s", string1, string2);

join_strings(string1, string2);

printf("\n\nThe concatenated string is %s\n\n", string1);

break;

case 3:

printf("\n\nEnter two strings: \t ");

scanf("%s \n %s", string1, string2);

compare_strings(string1, string2);

break;

case 4:

return 0;

default: printf("\n\nInvalid choice");

int find_length (char string[])

int len = 0, i;

for ( i = 0 ; string[i] != '\0' ; i++ )

len++;

Nisha S K, Dept. of ECE, SVIT Page 48


Module-4: Strings and Pointers

return len;

void join_strings(char string1[], char string2[])

int i, j;

i = find_length(string1);

for ( j = 0 ; string2[j] != '\0' ; i++, j++)

string1[i] = string2[j];

string1[i] = '\0';

int compare_strings(char string1[], char string2[])

int i = 0;

while (string1[i] == string2[i] && string1[i] != '\0')

i++;

if (string1[i] > string2[i])

printf("string1 > string2");

printf("\nStrings are not equal");

else if (string1[i] < string2[i])

printf("string1 < string2");

printf("\nStrings are not equal");

Nisha S K, Dept. of ECE, SVIT Page 49


Module-4: Strings and Pointers

else

printf("string1 = string2");

printf("\nStrings are equal");

return 0 ;

Output1:

1.Find Length

2.Concatenate

3.Compare

4.Exit

Enter your choice: 1

Enter the string: Classroom

The length of string is 9

Output2:

Enter your choice: 2

Enter two strings: Class

room

The concatenated string is Classroom.

Output3:

Enter your choice: 3

Enter two strings: Class

Nisha S K, Dept. of ECE, SVIT Page 50


Module-4: Strings and Pointers

room

string1 < string2

Strings are not equal

Write a C program to reverse a string and check whether it is palindrome or not

#include <stdio.h>

#include <string.h>

int main()

char Str[100], RevStr[100];

int i, j, len,flag=1;

printf("\n Please Enter any String : ");

scanf("%s",Str);

j = 0;

len = strlen(Str);

for (i = len - 1; i >= 0; i--)

RevStr[j++] = Str[i];

RevStr[j] = '\0';

printf("\n String after Reversing = %s\n", RevStr);

for(i=0;i<len;i++)

if(Str[i] != RevStr[i])

flag=0;

Nisha S K, Dept. of ECE, SVIT Page 51


Module-4: Strings and Pointers

if(flag == 1)

printf("The string is Palindrome\n");

else

printf("The string is not Palindrome\n");

return 0;

Output1:

Please Enter any String : MADAM

String after Reversing = MADAM

The string is Palindrome

Output2:

Please Enter any String : HELLO

String after Reversing = OLLEH

The string is not Palindrome

*****End*****

Nisha S K, Dept. of ECE, SVIT Page 52

You might also like