Taking first uppercase character of a multiple splitted string - java

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
}
}

Related

with help of only charAt() and isSpaceChar() make first latter uppercase in java

I want to use only charAt() and toUpperCase() function and capitalize the first letter of each word in a sentence.
Like make the letter capital, that is just after the space.
I tried with this following code.
import java.util.Scanner;
class firstscap
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
String s=sc.nextLine();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(Character.isSpaceChar(c))
{
char ch=s.charAt(++i);
ch=ch.toUpperCase();
}
}
System.out.println(s);
}
}
Several problems here.
s.charAt(n) gives you the n-th character of the String, not a pointer to the n-th character of the String. Changing that character does nothing to the String.
Also Strings are not mutable, which means you have no way to change them.
You can start build a new String from parts of the old String plus the Chars you have made uppercase.
You are capitalizing the characters but not storing them anywhere. I recommend you append all the characters to a StringBuilder*.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine().trim(); // Input & omit leading/trailing whitespaces
StringBuilder sb = new StringBuilder();
// Append the first character, capitalized
if (s.length() >= 1) {
sb.append(Character.toUpperCase(s.charAt(0)));
}
// Start with character at index 1
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isSpaceChar(c)) {
sb.append(c).append(Character.toUpperCase(s.charAt(++i)));
} else {
sb.append(c);
}
}
s = sb.toString();
System.out.println(s);
}
}
A sample run:
Enter a sentence: hello world how are you?
Hello World How Are You?
* You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.
Strings are immutable, you can't modify them.
Consider building a new String for the result e.g by using StringBuilder.
In the following example, a boolean flag is used to know if the last character was a space .
Also we check if the current character is a letter before putting it to upper case, otherwise it makes no sense.
This will also prevent possible crashes if the line ends with a space (since index charAt(i+1) would crash):
public static void main(final String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a sentence");
String s = sc.nextLine();
boolean wasSpace = false;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (wasSpace && Character.isLetter(c)) {
resultBuilder.append(Character.toUpperCase(c));
} else {
resultBuilder.append(c);
}
wasSpace = Character.isSpaceChar(c);
}
System.out.println(resultBuilder.toString());
}
Note :
If you also want the first letter of the whole sentence to be capitalized, just initialize wasSpace to true .
import java.util.Scanner;
public class A {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the string: ");
String a1 = (obj.nextLine()).trim();
String s1 = "";
char c2;
char arr[] = a1.toCharArray();
for (int i = 0; i <= a1.length() - 1; i++) {
if (Character.isSpaceChar(arr[i]) == true) {
++i;
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + " " + c2;
} else {
if (i == 0) {
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + "" + c2;
} else {
s1 = s1 + arr[i];
}
}
}
System.out.println(s1);
}
}

How to capitalize the first letter of a string in a sentence?

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 ?

Given a string,s ,split the string into tokens

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);
}
}
}
}

Java: how to print a dataset of strings as entered except in reverse order?

This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.

Reading the number of non-blank characters within string

This is my simple code.
import java.util.Scanner;
public class WordLines
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
String s;
System.out.println("Enter text from keyboard");
s = myScan.nextLine();
System.out.println("Here is what you entered: ");
System.out.println(s.replace(" ", "\n"));
}
}
If I were to enter a sentence such as "Good Morning World!" (17 non-blank characters in this line)
How could I be able to display my text and on top of that print out the number of non-blank characters present.
Use a regex to delete all whitespace (spaces, newlines, tabs) and then simply take the string length.
input.replaceAll("\\s+", "").length()
Try this:
System.out.println(s);
System.out.println(s.replace(" ", "").length());
Do something like:
public static int countNotBlank(String s) {
int count = 0;
for(char c : s.toCharArray()) {
count += c == ' ' ? 0 : 1;
}
return count;
}
you can calculate non blank characters from a String as follow:
int non_blank_counter = 0;
//your code to read String
for(int i=0;i<s.length();i++){
// .. inside a loop ..//
if ( myStr.charAt( i ) != ' ' )
non_blank_counter++;
}
System.out.println("number of non blank characters are "+non_blank_counter);
Another way to deal with it
import java.util.Scanner;
public class WordLines {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String s;
System.out.println("Enter text from keyboard");
s = myScan.nextLine();
String[] splitter = s.split(" ");
int counter = 0;
for(String string : splitter) {
counter += string.length();
}
System.out.println("Here is what you entered: ");
System.out.println(counter);
}
}
import java.util.Scanner;
public class WordLines
{
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String s="";
System.out.println("Enter text from keyboard");
while(myScan.hasNextLine()) s = s+myScan.nextLine();
System.out.println("Here is what you entered: ");
System.out.println(s.replace(" ", "\n"));
}
}
u need to user CTRL+C at last when u want to exit from input.
Hope this will help you if you just want to know the number of non blank character.
String aString="Good Morning World!";
int count=0;
for(int i=0;i<aString.length();i++){
char c = aString.charAt(i);
if(c==' ') continue;
count++;
}
System.out.println("Total Length is:"+count);

Categories