Write a program to implement strstr using array.
Algorithm Explanation
![]() | Pass two strings to the utility function. |
![]() | Take length of two strings and iterate the string. |
![]() | Find the substring from the second string. Return and print the string. |
Source Code
package com.dsacode.DataStructre.array; public class StrStrArray { public String strStr(String haystack, String needle) { int needleLen = needle.length(); int haystackLen = haystack.length(); if (needleLen == haystackLen && needleLen == 0) return ""; if (needleLen == 0) return haystack; for (int i = 0; i < haystackLen; i++) { if (haystackLen - i + 1 < needleLen) return null; int k = i; int j = 0; while (j < needleLen && k < haystackLen && needle.charAt(j) == haystack.charAt(k)) { j++; k++; if (j == needleLen) return haystack.substring(i); } } return null; } public static void main(String[] args) { StrStrArray s = new StrStrArray(); System.out.println("Implement strstr function and pass 'Helloworld' and 'vlow' arguments"); String strres = s.strStr("Helloworld", "low"); System.out.println("Result String: "+ strres); } }
Output
Implement strstr function and pass 'Helloworld' and 'vlow' arguments Result String: loworld