Program Discussion :: Strings
24 / 60
Write an efficient program to find the substring in a main string.
Answer:
#include
#include
using namespace std;
int main()
{
int i,j,temp;
char str[100]={"This is a pattern matching"};
char substr[20]={"pattern"};
for(i=0;str[i]!='\0';i++)
{
j=0;
if(str[i]==substr[j])
{
temp=i+1;
while(str[i]==substr[j])
{
i++;
j++;
}
if(substr[j]=='\0')
{
cout
Asked In ::
Language:
Madhu
15 Jun, 2017 10:12 AM
<!DOCTYPE html>
<html>
<body>
<?php
function Substring() {
$str ="ram says hello";
$search ="hello";
$flag=0;
echo "Input string is :" . $str."<br/>";
echo "substring for searching is :" . $search."<br/>";
$strlength1= strlen ($str) ;
$strlength2= strlen ($search) ;
for ($i = 0; $i <= $strlength1 - $strlength2; $i++)
{
for ($j = $i; $j < $i + $strlength2; $j++)
{
$flag = 1;
if ($str[$j] != $search[$j - $i])
{
$flag = 0;
break;
}
}
if ($flag == 1)
break;
}
if ($flag == 1)
printf("SEARCH SUCCESSFUL!");
else
printf("SEARCH UNSUCCESSFUL!");
}
Substring() ;
?>
</body>
</html>
Language:
Lokeshwari
7 Jul, 2017 9:30 AM
#include<stdio.h>
int main()
{
int i,j,temp;
char str[100]={"This is a pattern matching"};
char substr[20]={"pattern"};
for(i=0;str[i]!='\0';i++)
{
j=0;
if(str[i]==substr[j])
{
temp=i+1;
while(str[i]==substr[j])
{
i++;
j++;
}
if(substr[j]=='\0')
{
printf("The substring is present in given string at position %d\n",temp);
exit(0);
}
else
{
i=temp;
temp=0;
}
}
}
if(temp==0)
printf("The substring is not present in given string\n");
return 0;
}
Language:
Nikhil
7 Jul, 2017 9:30 AM
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int i,j,temp;
char str[100]={"This is a pattern matching"};
char substr[20]={"pattern"};
for(i=0;str[i]!='\0';i++)
{
j=0;
if(str[i]==substr[j])
{
temp=i+1;
while(str[i]==substr[j])
{
i++;
j++;
}
if(substr[j]=='\0')
{
cout<<"The substring is present in given string at position "<<temp<<"\n";
exit(0);
}
else
{
i=temp;
temp=0;
}
}
}
if(temp==0)
cout<<"The substring is not present in given string\n";
return 0;
}
Language:
Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.io.*;
public class Substring
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string: ");
String str=br.readLine();
int n=str.length();
System.out.println("Enter the beginIndex: ");
int beginIndex=Integer.parseInt(br.readLine());
System.out.println("Enter the endIndex: ");
int endIndex=Integer.parseInt(br.readLine());
if((beginIndex>=0 && endIndex>=0)&&(beginIndex<=n && endIndex<=n)&&(beginIndex<endIndex))
{
System.out.println("Substring is: "+str.substring(beginIndex,endIndex));
}
else
System.out.println("Wrong inputs");
}
}