java - Finding the index of each character in a substring -
java - Finding the index of each character in a substring -
i sense logic decent here; don't sense i'm lost. however, know i'm doing wrong. can find index of start of substring, can never find total count (ex. 3,4,5,6) of index of whatever word user enters substring.
i have been struggling week trying figure out how on own, can't right.
import java.util.scanner; public class midterm { public static void main (string[] args) { scanner keyboard = new scanner(system.in); string simplephrase; string portionphrase; int portionindex; int portioncount; int portionindextotal; system.out.println("enter simple phrase:"); simplephrase = keyboard.nextline(); int phraselength = simplephrase.length(); system.out.println("phrase length:" +phraselength); system.out.println("enter portion of previous phrase:"); portionphrase = keyboard.nextline(); string portionphrasesub = simplephrase.substring(portionphrase); portionindex = simplephrase.indexof(portionphrasesub); (portionindex; portionindex <= portionphrase; portionindex++) { system.out.println("portion phrase index:"+portionindex); } } }
i'm still confused on want. there 2 simple things know , seem making more complicated needs be.
to index of single character, such "c" in word "acorn", this:
string s = "acorn"; int cindex = s.indexof("c"); system.out.println("the index of c is: " + cindex);
if want see if string contains chunk, utilize exact same method. if looking @ word "acorn" 1 time again , want see "orn" happens, you'd this:
string s = "acorn"; int ornindex = s.indexof("orn"); system.out.println("the index of orn is: " + ornindex);
remember indexes start 0 in java, index of "a" in "acorn" 0, of "c" 1, of "o" 2, , on.
i hope helps. luck :)
edit: commented this: "i guess, question 1 code compile, how go counting every single letter of substring?"
i'll reply best can, though again, still confusing question.
what mean count" every letter? if want break word individual letters, can this:
string s = "acorn"; char[] characters = new char[s.length()-1]; for(int = 0; < s.length() - 1; i++) { char[i] = s.charat(i); }
but have no clue why you'd want that...you can access character in string @ given index string.charat(index), or if want have string result, string.substring(index, index+1)
java string indexing substring
Comments
Post a Comment