Java Read Input String and Display with space - java

I'm trying to Display one String Which is User Input.
Display With Space and starting letter of the word as Upper Case.
For example If the user input is like mobileScreenSize output Will be Mobile Screen Size.
Any help Thankful to Them.

To be able to split the input into valid words you need a dictionary of valid words.
With such a dictionary you can first split the input in words and in a second pass uppercase the first letters.

1. Thanks a lot for all your support guys
2. Finally I found the solution.
----------
package demo.practice.java;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
System.out.println("Enter String");
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
//split into words
String[] words = input.split("(?=[A-Z])");
words[0] = capitalizeFirstLetter(words[0]);
//join
StringBuilder builder = new StringBuilder();
for ( String s : words ) {
builder.append(s).append(" ");
}
// System.out.println(builder.toString());
System.out.println("Output String--->" +builder.toString());
}
private static String capitalizeFirstLetter(String in) {
return in.substring(0, 1).toUpperCase() + in.substring(1);
}
}

Related

split(" ") user text string and printing the first letter in each approved word

The user is supposed to enter multiple words (without regards to lower/uppercase) with space inbetween, this text will then be translated into initials without any spaces included. However, I only want the initials of the words that I approve of, if anything but those words, the printout will instead say "?" instead of printing the first alphabet of a word. E.q: "hello hello hello" will come out as: "HHH", but "hello hi hello" or "hello . hello" will instead result in "H?H".
I've managed to make it print out the initials without the spaces. But I can't figure out how to add a condition where the program would first check whether the input contains unapproved words or signs/symbol or not in order to replace that unapproved or non-word with a question mark instead of just going ahead and printing the initial/sign. I've tried placing the for-loop inside an if-else-loop and using a switch()-loop but they won't interact with the for-loop correctly.
public static void main (String []args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
System.out.print(i.charAt(0));
}
}
So what happens right now is that regardless what words the user enter, the initials of each word or symbol/sign will be printed regardless.
You should create a set of approved words and then check whether each word, entered by the user, makes part of this set.
Something like this:
...
Set<String> approved_words = new TreeSet<>();
approved_words.add("HELLO");
approved_words.add("GOODBYE");
...
for (String i : parts) {
if (approved_words.contains(i))
System.out.print(i.charAt(0));
else
System.out.print('?');
}
System.out.println();
Small suggestion:
You may want to allow the user to enter multiple spaces between the words.
In that case, split the words like this: str.split(" +")
If you want to filter against words you dislike, you will have to code it.
Like the example with "hi":
public static void main (String []args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if(!"HI".equals(i))
System.out.print(i.charAt(0));
else
System.out.print("?");
}
}
Of course in real life you want such comparison on a collection, preferably something fast, like a HashSet:
public static void main (String []args) {
Set<String> bannedWords=new HashSet<String>(Arrays.asList("HI","."));
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if(!bannerWords.contains(i))
System.out.print(i.charAt(0));
else
System.out.print("?");
}
}
(this one bans 'hi' and '.')
You could create a simple Set containing all the words that you accept. Then in your for loop, for every String i you check if the set contains ``i```. If this is true, you print out i.charAt(0). Otherwise you print out "?".
I could provide code for this if necessary, but it's always good to figure it out yourself ;)
Supposed you provide unapproved words as input arguments
public static void main (String []args) {
Set<String> unapprovedSet = new HashSet<>(Arrays.asList(args));
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String[] parts = input.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if (unapprovedSet.contains(i)) {
System.out.print("?");
} else {
System.out.print(i.charAt(0));
}
}
}

BlueJ string issue

I'm trying to create a program in BlueJ that allows the reader to type any word, then print out: that word, the length of the word, and whether or not the word contains "ing". I've figured out how to print the word and its length, but I can't figure out how to include whether "ing" is in the word.
Here is my code:
import java.util.*;
public class One
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "";
System.out.println("Type in a word");
str = sc.nextLine();
//System.out.println(str);
System.out.println(str.length());
}
}
How can I tell whether "ing" is included in the word?
You can do that using the contains() method on your resulting string:
if (str.contains("ing")) System.out.println("Contains ING");
If you need to match either lowercase or uppercase, you can just convert str to upper case and check that instead:
if (str.toUpperCase().contains("ING")

Why does my Java StringTokenizer read emptyspace?

I wrote this program that should only break down the string when there is greater than sign or a colon. When I enter for example "cars:ford> chevy" , the output gives me the space between the > and "chevy" and then the word "chevy. How do I prevent it from giving me that white space? All I want is the word , here is my code.
import java.util.Scanner;
import java.util.StringTokenizer;
public class wp{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter words");
String ingredients = keyboard.nextLine();
StringTokenizer str = new StringTokenizer(ingredients,">:");
while(str.hasMoreTokens()){
System.out.println(str.nextToken());
}
}
}
As the space is part of the input, it is valid that the tokenizer returns it (think of situations where you want to react to the space).
So all you need to do is postprocess your split results e.g.:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter words");
String ingredients = keyboard.nextLine();
StringTokenizer str = new StringTokenizer(ingredients, ">:");
while (str.hasMoreTokens()) {
String nextToken = str.nextToken();
String trimmed = nextToken.trim();
System.out.println(trimmed);
}
}
}
Answer to trim is ok also, but on line
StringTokenizer str = new StringTokenizer(ingredients, ">:");
you specified delimiters as characters '>' and ':', you can simply add space there too. It depends what your requirements are. If you want for string "cars:ford> chevy 123" to have 4 tokens, this is what you have to do...
So change it to
StringTokenizer str = new StringTokenizer(ingredients, ">: ");
You can use trim() method of String class to remove all preceding and succeeding white spaces:
str.nextToken().trim().

How to split the string (by matching a set of regular expression) into tokens and print each token in JAVA?

Problem Statement
Given a string s , matching the regular expression [A-Za-z !,?._'#]+, split the string into tokens. We define a token to be one or more consecutive English alphabetic letters. Then, print the number of tokens, followed by each token on a new line.
Input Format
A single string, s.
s is composed of English alphabetic letters, blank spaces, and any of the following characters: !,?._'#
Output Format
On the first line, print an integer,n, denoting the number of tokens in string s (they do not need to be unique). Next, print each of the n tokens on a new line in the same order as they appear in input string s .
Sample Input
He is a very very good boy, isn't he?
Sample Output
10
He
is
a
very
very
good
boy
isn
t
he
My Code:
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
String[] splitString = (s.replaceAll("^[\\W+\\s+]", "").split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string);
}
}
}
This code works fine for the Sample Input but do not pass this test case.
Test case:
Input:
YES leading spaces are valid, problemsetters are evillllll
Expected Output:
8
YES
leading
spaces
are
valid
problemsetters
are
evillllll
What changes in the code will pass this test case ?
Speaking about trimming non-word chars in the beginning of the string, your regex is not correct.
The ^[\\W+\\s+] matches 1 character at the beginning of a string, either a non-word (\W), a + or a whitespace. Using replaceAll makes no sense since only 1 char at the start of the string will get matched. Also, \W actually matches whitespace characters, too, so there is no need including \s into the same character class with \W.
You may replace that .replaceAll("^[\\W+\\s+]", "") with .replaceFirst("^\\W+", ""). This will remove 1 or more non-word chars at the beginning of the string (see this regex demo).
See this online Java demo yielding your expected output.
NOTE: to split a sentence into word char chunks, you may actually use
String[] tokens = s.replaceFirst("^\\W+", "").split("\\W+");
Java demo:
String s = " YES leading spaces are valid, problemsetters are evillllll";
String[] splitString = s.replaceFirst("^\\W+", "").split("\\W+");
Then,
System.out.println(splitString.length); // => 8
for (String string : splitString) {
System.out.println(string);
}
// => [ YES, leading, spaces, are, valid, problemsetters, are, evillllll]
Try this one it's working
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
s = s.trim();
if (s.length() == 0) {
System.out.println(0);
} else {
String[] strings = s.split("['!?,._# ]+");
System.out.println(strings.length);
for (String str : strings)
System.out.println(str);
}
}
}
You can trim the string before splitting it. In the given test case, it will count blankspace at the starting of the string as well. Try this:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine().trim();
if(s.isEmpty())
System.out.println("0");
else {
String[] S = s.split("[\\s!,?._'#]+");
System.out.println(S.length);
for(int i=0;i<S.length;i++) {
System.out.println(S[i]);
}
}
scan.close();
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
StringTokenizer st = new StringTokenizer(s,("[_\\#!?.', ]"));
System.out.println(st.countTokens());
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
scan.close();
}
if(s.trim().isEmpty()){
System.out.println("0");
System.out.println(s);
} else {
String[] splitString = (s.replaceAll("^\\W+", "").split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for(String str: splitString) {
System.out.println(str);
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
String[] arr = s.split("\\s+|\\,+|\\'+|[\\-\\+\\$\\?\\.#&].*");
// Write your code here.
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
scan.close();
}
}
The following should help
public static void regexTest() {
String s="isn't he a good boy?";
// Replace any non alphabetic characters with a space.
// [^a-zA-Z]
// [ - Start a custom character class
// ^ - Anything that is not
// a-zA-Z - a lowercase character or upper case character.
// for example a-z means everything starting from 'a' up to
// and including 'z'
// ] - End the custom character class.
// Given the input string, the single quote and question mark will be replaced
// by a space character.
s=s.replaceAll("[^a-zA-Z]", " ");
// Split the string (that only contains letters and spaces into individual words.
String[] array_s=s.split(" ");
for(int i=0;i<array_s.length;i++) {
System.out.println(array_s[i]);
}
This will pass all test cases
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if(s.trim().isEmpty()) {
System.out.println(0);
}
else {
System.out.println(s.trim().split("[!,?. #_']+").length);
for(String a : s.trim().split("[!,?. #_']+")){
System.out.println(a);
}
}
scan.close();
}
}

How to show sentence word by word in a separate line

The sentence String is expected to be a bunch of words separated by spaces, e.g. “Now is the time”.
showWords job is to output the words of the sentence one per line.
It is my homework, and I am trying, as you can see from the code below. I can not figure out how to and which loop to use to output word by word... please help.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
int space = sentence.indexOf(" ");
sentence = sentence.substring(0,space) + "\n" + sentence.substring(space+1);
System.out.println(sentence);
}
}
You're on the right path. Your showWords method works for the first word, you just have to have it done until there are no words.
Loop through them, preferably with a while loop. If you use the while loop, think about when you need it to stop, which would be when there are no more words.
To do this, you can either keep an index of the last word and search from there(until there are no more), or delete the last word until the sentence string is empty.
Since this is a homework question, I will not give you the exact code but I want you to look at the method split in the String-class. And then I would recommend a for-loop.
Another alternative is to replace in your String until there are no more spaces left (this can be done both with a loop and without a loop, depending on how you do it)
Using regex you could use a one-liner:
System.out.println(sentence.replaceAll("\\s+", "\n"));
with the added benefit that multiple spaces won't leave blank lines as output.
If you need a simpler String methods approach you could use split() as
String[] split = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : split) {
if (word.length() > 0) { // eliminate blank lines
sb.append(word).append("\n");
}
}
System.out.println(sb);
If you need an even more bare bones approach (down to String indexes) and more on the lines of your own code; you would need to wrap your code inside a loop and tweak it a bit.
int space, word = 0;
StringBuilder sb = new StringBuilder();
while ((space = sentence.indexOf(" ", word)) != -1) {
if (space != word) { // eliminate consecutive spaces
sb.append(sentence.substring(word, space)).append("\n");
}
word = space + 1;
}
// append the last word
sb.append(sentence.substring(word));
System.out.println(sb);
Java's String class has a replace method which you should look into. That'll make this homework pretty easy.
String.replace
Update
Use the split method of the String class to split the input string on the space character delimiter so you end up with a String array of words.
Then loop through that array using a modified for loop to print each item of the array.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
String[] words = sentence.split(' ');
for(String word : words) {
System.out.println(word);
}
}
}

Categories

Resources