Tech Rocks

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more...

Friday, February 21, 2014

IndexOf Logic in Java

Logic of the following function:

IndexOf(String,Sub String) – Gives the position of the first occurrence of the substring.

Please check and comment.

import java.io.IOException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class TestIndexOf extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("String IndexOf Implementation...");

resp.getWriter().println("Pos = " + IndexOf("Hello Jeetu", "llo"));

}

public int IndexOf(String main, String sub) {

char[] mainc = main.toCharArray();
char[] subc = sub.toCharArray();

for (int i = 0; i < mainc.length; i++) {
if (mainc[i] == subc[0]) {
for (int j = 0; j < subc.length; j++) {
if (mainc[i + j] != subc[j])
break;
else if (j == subc.length - 1)
return i + 1;
}

}
}
return -1;
}
}

0 comments :