Im basically just trying to replace the character '$' with words that I have in this array. I also want it so that every time that character appears, it goes to the next word in the array.
Example:
Array = ("BEAR", "RICE", "STEAK")
String = "He$$$llo"
Output: HeBEARRICESTEAKllo
AS you can see, it goes down sequentially through the array.
This is the code I have.
private static String[] stickers= {"PUMPKIN", "BAT", "WITCH", "BAT"};
public static void main(String[] args) {
int count=0;
char search = '$';
String data_type,data,replacedata,updated_data;
Scanner scan = new Scanner(System.in);
do{
System.out.println("What type of data?");
data_type=scan.nextLine();
String updated_datatype = data_type.toLowerCase().replaceAll("\\s","");
System.out.println("Type your message: ");
data=scan.nextLine();
for(int i=0;i<data.length();i ){
if(data.charAt(i)==search)
count ;
}
for(int j=0;j<count;j ){
updated_data = data.replace("$", stickers[j]);
System.out.println("Your updated message is: " updated_data);
}
//System.out.println("Your word: " data " ,has this many occurances of $: " count);
//replacedata=data.replace('$', replacement'')
//if (data_type=="name");
}while(data_type!="exit");
}
All this does for me is replace the all the characters with the element thats being iterated through the array.
Also, as you can tell, im fairly new to java and programming overall. Thanks!!
CodePudding user response:
Read the javadoc for String.replace
. What does it say it does?
Look at other methods on String
with replace
in their name, is there a more suitable one? What's special about its first parameter?
Step through your code with the debugger. Figure out why changes made to the string on the first pass through the loop don't appear after the second pass.
CodePudding user response:
Try this.
static Pattern PAT = Pattern.compile("\\$");
static String replaceWords(String s, String[] stickers) {
Iterator<String> it = Arrays.stream(stickers).iterator();
return PAT.matcher(s).replaceAll(m -> it.next());
}
and
String[] stickers= {"BEAR", "RICE", "STEAK"};
String s = "He$$$llo";
System.out.println(replaceWords(s, stickers));
output:
HeBEARRICESTEAKllo