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
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();
}
}
Comments
Leave a comment