Interview Question
Developer Program EngineersCountry: United States
Interview Type: Phone Interview
String str = "CSK lost to RR";
String subString = "CSK";
int subLength = subString.length();
int count = 0;
int j = 0;
for(int i = 0 ; i < str.length(); ++i) {
if(str.charAt(i) == subString.charAt(j)) {
++j;
if(j == subLength) {
++count;
j=0;
}
}else {
j = 0;
}
}
System.out.println(subString +" is present at "+ count +" places.");
Please make comment if solution is not correct.
CODE FOR SEARCHING ,COUNTING,INDEX OF SUBSTR IN STR:
import java.io.*;
public class Subbu{
public static void main(String args[]){
String str = "CSK lost to RR";
String subString = "CSK";
int i,count;
for(i = 0 ; i < str.length(); ++i) {
if(str.charAt(i) == subString.charAt(i)) {
count=++i;
System.out.println("yes,str contains substr and also substr found at index of "+ count);
}
else{
System.out.println("no, str doesnt contains substr");
}}}}
OUTPUT:
yes,str contains substr and also substr found at index of 1
yes,str contains substr and also substr found at index of 3
Hmm.. ok....
Fix this code. That's your homework.
- S O U N D W A V E October 05, 2013