Insert
Character Word in any Desired Location in a String
#include
#include
#include
void main()
{
int i, j, count = 0, pos, flag = 0;
char s1[100], s2[10], s3[100];
char *ptr1, *ptr2, *ptr3;
clrscr();
printf("\nenter the String:");
scanf(" %[^\n]s", s1);
printf("\nenter the string to be inserted:");
scanf(" %[^\n]s", s2);
printf("\nenter the position you like to insert:");
scanf("%d", &pos);
ptr1 = s1;
ptr3 = s3;
for (i = 0, j = 0;*ptr1 != '\0'; ptr1++, i++, j++, ptr3++)
{
s3[j] = s1[i];
if (*ptr1 == ' ' && flag != 1)
++count;
if (flag != 1 && count == pos - 1)
{
flag = 1;
for(ptr2 = s2;*ptr2 != '\0'; ptr2++)
{
s3[++j] = *ptr2;
ptr3++;
}
s3[++j] = ' ';
ptr3++;
}
}
s3[j] = '\0';
printf("\nthe string after modification is\n\n %s\n", s3);
getch();
}
Output
enter the string:Welcome to Sanfoundry's C Programming Class, Welcome Again to C Class!
enter the word to insert:Sanfoundry's
enter the position you like to insert:3
the string after modification is
Welcome to Sanfounsry's Sanfoundry's C Programming Class, Welcome Again to C Class!
Find the First Occurence of the any Character of String2 in String1
#include
#include
void main()
{
char s1[50], s2[10];
int i, flag = 0;
char *ptr1, *ptr2;
clrscr();
printf("\nenter the string1:");
scanf(" %[^\n]s", s1);
printf("\nenter the string2:");
scanf(" %[^\n]s", s2);
for (i = 0, ptr1 = s1;*ptr1 != '\0';ptr1++)
{
i++;
for (ptr2 = s2; *ptr2 != '\0';ptr2++)
{
if (*ptr1 == *ptr2)
{
flag = 1;
break;
}
}
if (flag == 1)
break;
}
if (flag == 1)
printf("\nfirst occurance of character of string2 in string1 is at position:%d and character is %c", i, *ptr2);
else
printf("\nnone of the characters of string1 match with mone of characters of string2");
getch();
}
Output
enter the string1:C Programming Class
enter the string2:rnp
first occurance of character of string2 in string1 is at position:3 and character is p
Implement strpbrk() Function
#include
#include
char* strpbrk(char *, char *);
int main()
{
char string1[50], string2[50];
char *pos;
clrscr()l
printf("Enter the String:\n");
scanf(" %[^\n]s", string1);
printf("\nEnter the Character Set:\n");
scanf(" %[^\n]s", string2);
pos=strpbrk(string1, string2);
printf("%s", pos);
}
char* strpbrk(char *string1, char *string2)
{
int i, j, pos, flag = 0;
for (i = 0; string1[i] != '\0';i++);
pos = i;
for (i = 0;string2[i] != '\0';i++)
{
for (j = 0;string1[j] != '\0';j++)
{
if (string2[i] == string1[j])
{
if ( j <= p1)
{
pos = j;
flag = 1;
}
}
}
}
if (flag == 1)
{
return &string1[pos];
}
else
{
return NULL;
}
getch();
}
Output
Enter the String:
C programming Class
Enter the Character Set:
mp
programming Class
No comments:
Post a Comment