Question #297671

Write a function that takes an input parameter as a String. The function should replace the alternate words in it with “xyz” and print it. Words are separated by dots. (Avoid using inbuilt function) If input is “i.like.this.program.very.much” Output will be “i.xyz.this.xyz.very.xyz” in java


Expert's answer



import java.util.*;


class App {


	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("Enter a String: ");
		String s = in.nextLine();
		int length = s.length();
		String word = "";
		int position = 0;
		for (int i = 0; i < length; i++) {
			char c = s.charAt(i);
			if (c != '.') {
				word = word + c;
			} else {
				position++;
				if (position % 2 == 0) {
					System.out.print("xyz.");
				} else {
					System.out.print(word + ".");
				}


				word = "";
			}
			if (i == length - 1) {
				position++;
				if (position % 2 == 0) {
					System.out.print("xyz");
				} else {
					System.out.print(word);
				}
			}
		}


		in.close();
	}
}

LATEST TUTORIALS
APPROVED BY CLIENTS