Answer to Question #297623 in Java | JSP | JSF for Greta

Question #297623

Write a program to take a String as input then display the first and last letter of each word with a condition that if it is having one character then it will remain as it is using only indexOf() function.


For example:


Enter a String


ASia is A conTinEnT


Modified: Aa is A cT


Don't use array[] and split

1
Expert's answer
2022-02-14T12:56:33-0500


import java.util.*;


class App {


	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("Enter a String: ");
		String string = in.nextLine();
		String stringModified = "";
		int index = 0;
		stringModified = "";


		int prevIndex = 0;
		while (index != -1) {
			prevIndex = index;
			index = string.indexOf(' ', index);
			if (index != -1) {
				index++;
				if (((index - 1) - prevIndex) >= 2) {
					stringModified += "" + string.charAt(prevIndex) + string.charAt(index - 2) + " ";
				} else {
					stringModified += ("" + string.charAt(prevIndex)) + " ";
				}
			}
		}
		stringModified += "" + string.charAt(prevIndex) + string.charAt(string.length() - 1) + " ";
		System.out.println("Modified: " + stringModified);


		in.close();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS