You are to design a Java GUI application to read and display a text file of your
ID: 3637080 • Letter: Y
Question
You are to design a Java GUI application to read and display a text file of your choice and then allow the user to perform "search and replace" operations. The user may enter a string as the key for search and another string which replaces every occurrence of the key in the displayed text. The text should be re-displayed after each "search and replace". The "search and/or replace" methods in the String API are not allowed. You are required to design your own search and replace algorithms for this assignment.
Explanation / Answer
public class Main { public static java.lang.String replace ( final java.lang.String template, final java.util.Map map ) { final java.lang.StringBuilder list = new java.lang.StringBuilder( "\$(" ); for( final java.lang.String key: map.keySet() ) { list.append( key ); list.append( "|" ); } list.append( "[^\s\S])" ); java.util.regex.Pattern pattern = java.util.regex.Pattern.compile( list.toString() ); java.util.regex.Matcher matcher = pattern.matcher( template ); final java.lang.StringBuffer stringBuffer = new java.lang.StringBuffer(); while( matcher.find() ) { final java.lang.String string = matcher.group( 1 ); matcher.appendReplacement ( stringBuffer, map.get( string )); } matcher.appendTail( stringBuffer ); return stringBuffer.toString(); } public static void main( final java.lang.String[] args ) { final java.util.Map map = new java.util.HashMap(); map.put( "user", "Mary" ); map.put( "name", "Patricia" ); java.lang.System.out.println ( replace( "Hello $user, my name is $name.", map ) ); }}Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.