I 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.String 's' is composed of English alphabetic letters, blank spaces, and any of the following characters: !,?._'#
Here what I'm doing.
import java.io.*;
import java.util.*;
public class apples {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
String[] splitString = (s.split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string);
}
}
}
When I input a string starting with any of those above characters then my code is counting the character and while printing it gives a empty space, like this.
#dsd sd.sf
4
dsd
sd
sf
What I'm expecting is this.
#dsd sd.sf
3
dsd
sd
sf
Please Help!!
There is no text before the first separator so you get an empty string. I suggest you ignore the first empty string. You could also add a separator at the start so you know there is one you can always ignore. e.g.
String[] split = ("#"+s).split("\\W+");
int words = split.length - 1;
or you can truncate leading non letters
String[] split = s.replaceAll("^\\W+", "").split("\\W+");
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if (!scan.hasNext())
{
System.out.println(0);
}
else
{
String s = scan.nextLine();
scan.close();
s=s.replaceAll("^\\W+", "");
String[] words = s.split("[\\s',!?._#]+");
int len=words.length;
System.out.println(len);
for(String i:words)
{
System.out.println(i);
}
}
}
}
Related
I have the following code:
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String a;
System.out.println("Type in your pinochle deals: ");
a=sc.nextLine();
sc.close();
String[] deals=a.split("");
}
}
I need to split the String I named "a" into a 16 spaced array. But the problem with the splitting is that the input is something like this: ATKQQJ,AKQQ,KQQJN,A. I need to split this into 16 parts and save it to an array I named "deals." I've tried String[] deals=a.split("" && ","); but apparently that isn't valid. I've also tried to split String a into 2 separate arrays and then put them together, but I realized I didn't know how. I want the output to be ["A","T","K","Q","Q","J","A","K","Q","Q","K","Q","Q","J","N","A"] when the input is: ATKQQJ,AKQQ,KQQJN,A. How should I accomplish this?
Try this code
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
String a,b="";
System.out.println("Type in your pinochle deals: ");
a = sc.nextLine();
sc.close();
String[] temp = a.split(",");
for (int i=0; i<temp.length; i++){
for (int j=0; j<temp[i].length(); j++){
b+=temp[i].charAt(j);
}
}
char[] deals=new char[b.length()];
for (int i=0; i<b.length(); i++){
deals[i]=b.charAt(i);
}
}
}
//Split it out into individual characters
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").toCharArray()));
//Split it into strings of a single character
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").split("")));
Here you go:
String a = "ATKQQJ,AKQQ,KQQJN,A";
// Split the string into comma-separated parts
String[] parts = a.split(",");
//Join those parts into a single string
String whole = String.join("",parts);
//Finally, split it up into individual letters
String[] letters = whole.split("");
Could have also generated whole by removing the commas from a.
So I want to print out the first uppercase character when splitting my String when it reaches a special character.
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if(input.contains("-")){
for (int i = 0; i < input.length(); i++){
String[] parts = input.split("-",2);
String string1 = parts[0];
String string2 = parts[1];
System.out.print(string1.substring(0, 0) + string2.substring(0,0));
}
}
}
``
I'll give an example of what I'd like it to do.
> input: Please-WooRk-siR
> output: PW
> input: This-Is-A-Test
> output: TIAT
So only print the first uppercase character of each substring.
Any ideas? Thanks in advance :)
If you use regular expressions, you can use a zero-width negative lookahead to remove all characters that aren't capitals at the starts of words:
public static String capitalFirstLetters(String s) {
return s.replaceAll("(?!\\b[A-Z]).", "");
}
When you run the test cases:
public static void main(String[] args) throws Exception {
System.out.println(capitalFirstLetters("Please-WooRk-siR"));
System.out.println(capitalFirstLetters("This-Is-A-Test"));
}
It prints:
PW
TIAT
This is one way to do it.
String str = "This-Is-a-Test-of-The-Problem";
StringBuilder sb = new StringBuilder();
for (String s : str.split("-")) {
char c = s.charAt(0);
if (Character.isUpperCase(c)) {
sb.append(c);
}
}
System.out.println(sb.toString());
Update the code to this :
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.contains("-")) {
String[] parts = input.split("-");
for (String part: parts) {
System.out.print(Character.isUpperCase(part.charAt(0)) ? part.charAt(0) : "");
}
}
}
}
Output :
1.
Input : A-Ba
AB
2.
Input : A-aB
A
3.
Input : A
Now, your test case :
Input : This-Is-A-Test
TIAT
Another solution by utilizing javas streaming API
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.contains("-")) {
List<String> collect =
Stream.of(input.split("-")) // get a stream of words
.map(word -> word.substring(0, 1)) // get first character only
.filter(character -> character.toUpperCase().equals(character)) // only keep if character is uppercase
.peek(System.out::print) // print out character
.collect(Collectors.toList()); // just needed for stream to start
}
}
import java.util.Scanner;
public class String5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("cumleni daxil et:");
String a = sc.nextLine();
char [] b= new char [20];
if (a.endsWith("aioeuAIOEU")) {
a.getChars(1, 10, b, 0);
System.out.println(b);
Use a regular expression to check that:
if (a.matches("^.*[aeiouAEIOU]$"))
That will be true if the text in a ends with any of aeiouAEIOU
You can do the opposite and check if "aeiouyAEIOUY" contains the last letter of your string:
if ( "aeiouyAEIOUY".contains(a.substring(s.length()-1, a.length())))
Heres something that might be in line with what you are trying.
Like others have said its easier to find if the last character is one of the vowels by comparing the last character to a fixed set of lower and upper case vowels.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Test4 {
private static final List<Character> vowels = Arrays.asList('a','i','o','e','u','A','E','I','O','U');
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
if (vowels.contains(a.charAt(a.length()-1))){
System.out.println("Last character is a vowel");
}
}
}
I can't seem to find any solutions for this with just using String methods in Java. Having trouble trying to get the string out...
Heres my code:
import java.util.Scanner;
public class lab5_4
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s= scan.nextLine();
String s2 = s.toLowerCase();
for( int count = 0; count<= s2.length()-1; count++)
{
if( s2.charAt(count)==' ')
{
String s3 = s2.substring(count,count+1);
String s4= s3.toUpperCase();
System.out.print(s4);
}
}
}
}
The following method forces all characters in the input string into lower case (as described by the rules of the default Locale) unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.
public static String toDisplayCase(String s) {
final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
// to be capitalized
StringBuilder sb = new StringBuilder();
boolean capNext = true;
for (char c : s.toCharArray()) {
c = (capNext)
? Character.toUpperCase(c)
: Character.toLowerCase(c);
sb.append(c);
capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}
return sb.toString();
}
TEST VALUES
a string
maRTin o'maLLEY
john wilkes-booth
YET ANOTHER STRING
OUTPUTS
A String
Martin O'Malley
John Wilkes-Booth
Yet Another String
You seem to be checking for a whitespace and then calling toUpperCase() on that. You want s3 to be the next character, so it should be String s3 = s2.substring(count+1, count+2);.
You are also only printing characters where the if is evaluated as true instead of all characters. You need the print statement to be outside the if. This will require more than basic changes, but this should get you started.
you can use pattern to select the first letter from each sentence
here an exemple
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s= scan.nextLine();
String toCappital = capitalTheFirstLetter(s);
System.out.println(toCappital);
}
public static String capitalTheFirstLetter(String sentence){
StringBuilder stringBuilder = new StringBuilder(sentence.toLowerCase());
Pattern pattern = Pattern.compile("\\s?([a-z])[a-z]*"); // ([a-z]) to group the first letter
Matcher matcher = pattern.matcher(sentence.toLowerCase());
while (matcher.find()) {
String fistLetterToCapital = matcher.group(1).toUpperCase();
stringBuilder.replace(matcher.start(1), matcher.end(1), fistLetterToCapital); // replace the letter with it capital
}
return stringBuilder.toString();
}
}
the output
Enter a sentence
how to capitalize the first letter of a string in a sentence ?
How To Capitalize The First Letter Of A String In A Sentence ?
import java.util.Scanner;
public class WordLines {
public static void main(String [] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sca.nextLine();
int count = 0;
for(int j=0; j<s.length(); j++)
System.out.println(s.charAt(j));
}
}
I am trying to write a program that reads certain line from user input and then displays only one word from than sentence to new line at a time.
For example
Input: The hill is very-steep!!
It would print out
The
hill
is
very-steep!!
So far I have done this much!!
You should use method String::split(String) by regular expression "\s+"
String s = sca.nextLine();
System.out.println("Print out:");
for(final String word : s.split("\\s+"))
{
System.out.println(word);
}
Regular expression \\s+ means "One or more whitespaces in sequence"
Read more about regular expressions you can here