File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ class ReplaceWord {
4
+ // Main Method
5
+ public static void main (String [] args ) {
6
+ Scanner input = new Scanner (System .in );
7
+
8
+ System .out .print ("Enter a string: " );
9
+ String str = input .nextLine ();
10
+
11
+ System .out .print ("Enter a word to replace: " );
12
+ String wordToReplace = input .next ();
13
+
14
+ System .out .print ("Enter a word to replace with: " );
15
+ String wordToReplaceWith = input .next ();
16
+
17
+ // Method to replace a given word in string with another word
18
+ String result = replaceWord (str , wordToReplace , wordToReplaceWith );
19
+
20
+ System .out .println ("String after replacing word: " + result );
21
+
22
+ input .close ();
23
+ }
24
+
25
+ // Method to replace a given word in string with another word
26
+ public static String replaceWord (String str , String wordToReplace , String wordToReplaceWith ) {
27
+ String [] words = str .split (" " );
28
+ String result = "" ;
29
+ for (String word : words ) {
30
+ if (word .equals (wordToReplace )) {
31
+ result += wordToReplaceWith + " " ;
32
+ } else {
33
+ result += word + " " ;
34
+ }
35
+ }
36
+ return result ;
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments