Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Arrays and Strings
  5. Strings
  6. String Substring

String Substring

strstr()

strstr( ) function returns pointer to the first occurrence of the string in a given string. Syntax for strstr( ) function is given below.

char *strstr(const char *s1, const char *s2)

s1 â€” This is the main C string to be scanned.

s2 — This is the small string to be searched with-in haystack string.

Program: To find substring in a string

#include <stdio.h>
#include<string.h>
int main()
{
	char s1[100];
	char s2[100];
	char *ptr;
	puts("Enter string1");
	gets(s1);
	puts("Enter string2");
	gets(s2);
	ptr = strstr(s1,s2);
	if(ptr == NULL)
	{
	    puts("string not present");
	}
	else
	{
	    printf("string present at %s",ptr);
	}
	return 0;
}

Output

Enter string1
Knowlege is power
Enter string2
pow
string present at power

Program: String Palindrome

#include<stdio.h>
#include<string.h>
int main()
{
    char s[100];
    char r[100];
    int i=0,j=0;
    puts("Enter string");
    gets(s);
    /* compute string length */
    while(s[i] != '\0')
    {
        i++;
    }
    /* copy one string to another */
    while(i>0)
    {
	  i--;
        r[j] = s[i];
        j++;
    }
    r[j] = '\0'	
    /*compare reverse with original string */
    if(strcmp(r,s) == 0)
    {
        printf("%s is palindrome");
    }
    else
    {
        printf("%s is not palindrome");
    }
    return 0;
}

Output

Enter string
mam is palindrome

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments