Write a program to take a String as input then display the word in one column and its position on the String in another column.
Enter a String
Coronavirus was the Worst pandemic
Coronavirus \t 1
was \t 2
the \t 3
Worst \t 4
pandemic \t 5
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++;
System.out.println(word + "\t" + position);
word = "";
}
if (i == length - 1) {
position++;
System.out.println(word + "\t" + position);
}
}
in.close();
}
}
Comments
Leave a comment