java - How to find a specific occurrence of a string inside of a string -
the problem this, i'm trying find , 1 occurrence of string, when way can 1 using keyword occurs multiple times.
ex. 4 potato, 4 (string want), 4 house, 4 car
how string want, when can't type in keywords string might contain.
imagine trying take 1 paragraph out of essay.
i've tried stringy.replaceall(str1, str2); variable, no avail. happens replace of string (go figure name replace all)
package com.donovan.cunningham; import java.util.arraylist; import java.util.random; public class essaycreator { //creating varz private static string[] lf = {"happy", "sad", "unhappy", "atractive", "fast", "lazy"}; private static string[] op = {"estatic", "melhencohly", "depressed", "alluring", "swift", "lackadaisical"}; private static string pf = " "; private static string temp[]; private static string conv = " "; private static string comm = ", "; private static random random = new random(); private arraylist<string> array = new arraylist<string>(); public static void converter(string in) { in = in.replace(comm, conv); (int = 0; < lf.length; i++){ in = in.replace(lf[i], op[i]); } in = in.replace(conv, comm); //int rand = random.nextint(in.indexof(pf)); (int = 0; < in.indexof(pf); i++){ /* want exact string of essay i'd convert pf conv, , remove paragraph change order } */ } creategui.output.settext(in); sound.stopsound(); } }
thanks
your question not clear though. want (1) find occurrence string don't know or want (2) replace occurrence string know?
the naive way (1) chop text space , put them in string-to-integer hashmap calculate occurrence string. can scan hashmap find n-occurence strings
for (2), supposed know key string want find, can apply indexof(string str, int fromindex) in string recursively followed:
int occurencecount = 0; string input = "here text key_word1, key_word2, ...etc"; stringbuffer output = new stringbuffer(); int index = input.indexof("key_word"); int copiedindex = 0; for(index>0) { output.append(input.substring(copiedindex, index)); occurencecount++; if(occurencecount==4) //find 4th occurrence , replaced "new_key_word" { output.append("new_key_word") } else { output.append("key_word") } copiedindex = index+("key_word".length); index = input.indexof("key_word", index+("key_word".length)); if(index==-1) break; }
ref: https://docs.oracle.com/javase/7/docs/api/java/lang/string.html#indexof(java.lang.string,%20int)
not sure if had answered question though...
Comments
Post a Comment