Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to find string within a string using for loop in java?
    primarykey
    data
    text
    <p>I'm trying to find if user input <code>s</code> contains the second user input <code>s1</code> using for loops and if statements. I only want to use methods <code>.charAt()</code> and <code>.length</code> and not <code>.indexOf</code> to find if s1 is within s. Once I find whether <code>s</code> contains <code>s1</code> or not, I either want to return <code>.charAt()</code> where <code>s1</code> begins in <code>s</code>, or return <code>-1</code> if <code>s1</code> doesn't occur at all inside <code>s</code>.</p> <p>For example, <code>s = abcdefghi</code> &amp; <code>s1 = def</code>, it will return <code>3</code>.</p> <p>This is my code so far: It either returns <code>0</code> or <code>-1</code></p> <pre><code>package javaapplication5; import java.util.Scanner; class myStrings { String s, s1; void setMyStrings(String str, String str1) { s = str; s1 = str1; } int find() { int i, j; int r = -1; char ns = s1.charAt(0); int sp; int count = 1; for (i = 0; i &lt; s.length(); i++){ if (s.charAt(i) == ns) { sp = i;//starting point for (j = i+1; j &lt; s1.length(); j++) { ns += 1; if (s.charAt(j) == ns){ j++; count++; } if (count == s1.length()) r = sp; } } } System.out.println(r); return r; } } public class JavaApplication5 { public static void main(String[] args) { Scanner in = new Scanner(System.in); myStrings setS = new myStrings(); String s, s1; System.out.print("Enter s:"); s = in.nextLine(); System.out.print("Enter s1:"); s1 = in.nextLine(); setS.setMyStrings(s1, s1); setS.find(); } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload