What is the easiest way to get last word and remaining all words if the user enters multiple whitespaces?
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
i expect the output like lastWord = sentence
and firstWords = this is a
String listOfWords = "This is a sentence";
String lastWord = listOfWords.replaceFirst("^((.*\\s+)?)(^\\S+)\\s*$", "$3");
String firstWords = listOfWords.replaceFirst("^((.*\\s+)?)(^\\S+)\\s*$", "$2").trim();
Identify the last word as (\\S+)\\s*$ : non-spaces possibly followed by spaces at the end ($).
Works not when there is no word
Works when there is exactly one word
Works when there are spaces at the end
Here is quick fix for you. Check following code.
Input :
This is a sentence
Output :
First Words :This is a
Last Words :sentence
String test = "This is a sentence";
String first = test.substring(0, test.lastIndexOf(" "));
String last = test.substring(test.lastIndexOf(" ") + 1);
System.out.println("First Words :" + first);
System.out.print("Last Words :" + last);
Hope this solution works.
To add one more answer using regex to split the sentence at the last space:
String listOfWords = "This is a sentence";
String[] splited = listOfWords.split("\\s(?=[^\\s]+$)");
System.out.println(Arrays.toString(splited));
//output [This is a, sentence]
I am not saying it's a good solution, however you can get the solution with below way:
public static void main(String[] args) {
String listOfWords = " This is a sentence ";
listOfWords = listOfWords.trim().replaceAll("\\s+", " ");
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
String firstWord = listOfWords.substring(0, listOfWords.length() - lastWord.length());
System.out.println(lastWord.trim());
System.out.println(firstWord.trim());
}
You can use
System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices);
Please check this:
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
String[] others = Arrays.copyOfRange(b, 0, b.length - 1);
//You can test with this
for(int i=0;i< others.length;i++){
System.out.println(others[i]);
}
String listOfWords = "This is a sentence";
String first=listOfWords.substring(0,listOfWords.lastIndexOf(' '));
String last=listOfWords.substring(listOfWords.lastIndexOf(' ')+1);
Hope this might help you.
You can use Regular expression for perfect match
String listOfWords = "This is a sentence";
Pattern r = Pattern.compile("^(.+?)(\\s+)([^\\s]+?)$");
Matcher m = r.matcher(listOfWords);
while(m.find()){
System.out.println("Last word : "+ m.group(3));
System.out.println("Remaining words : "+ m.group(1));
}
Where pattern "^(.+?)(\s+)([^\s]+?)$" works like below
^(.+?) - match all characters including space from the start(^) of the sentence
(\s+) - match more than one space if present
([^\s]+?)$ - match the last word by ignoring the space till the end($)
Output:
Last word : sentence
Remaining words : This is a
One way I can think of is:
Trim the sentence using String#trim.
Using the String#lastIndexOf, find the position of the last whitespace in the sentence.
Split the substring until the last whitespace using \\s+ and join the resulting array using String#join.
Demo:
public class Main {
public static void main(String args[]) {
String sentence = " This is a sentence";
sentence = sentence.trim();
int index = sentence.lastIndexOf(" ");
if (index != -1) {
String allButLastWord = String.join(" ", sentence.substring(0, index).split("\\s+"));
System.out.println("First words: " + allButLastWord);
System.out.println("Last word: " + sentence.substring(index + 1));
} else {
System.out.println("Last word: " + sentence);
}
}
}
Output:
First words: This is a
Last word: sentence
Related
This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
Closed 2 years ago.
Expected result:
input = "heLlo wOrLd"
output= "Hello World"
Actual result:
output= "Hello world"
My code only capitalizes the first word of the sentence:
public static void main(String args[]) {
String input = "heLlo wOrLd";
String output = input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
System.out.println(output);
}
If you want to use streams, you could do this:
String output = Arrays.stream(input.split(" "))
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
This is fairly self-explanatory. It simply converts to a lower case string, splits on the white space and then replaces the first character of each word with the uppercase version.
String output = "";
for (String word : input.toLowerCase().split("\\s+")) {
output += word.replaceFirst(".",word.substring(0, 1).toUpperCase()) + " ";
}
System.out.println(output);
or streams (but not as efficient as the first method). It does the exact same thing but calls a collector to reassemble the string by joining with a space.
String output = Arrays.stream(input.toLowerCase().split("\\s+"))
.map(w -> w.replaceFirst(".",w.substring(0, 1).toUpperCase()))
.collect(Collectors.joining(" "));
System.out.println(output);
Try this :
String input = "heLlo wOrLd";
String a []= input.split(" ");
String output = "";
for (String s:a){
output = output + s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase() + " ";
}
System.out.println(output);
I presume that you'll try some other word sentences. This code is effective for any input.
String input = scanner.nextLine();
String[] array = input.split(" "); //separates the input by spaces
String output = "";
for (int i = 0; i < array.length; i++) {
String word = array[i];
String firstLetter = word.substring(0, 1).toUpperCase();
String otherLetters = word.substring(1, word.length()).toLowerCase();
word = firstLetter + otherLetters;
output += word + " ";
}
System.out.println(output);
Let's say a person's name has three words, I just wanna show the first two words using a TextView.
What's the easiest way to do that?
String name = "abc def geh ijk";
String twoWordsName;
Or String.substring()
String twoWordsName = name.substring(0, name.indexOf(' ', name.indexOf(' ')+1));
do this:
String name = "abc def geh ijk";
String[] result = name.split("\\s+");
first two words:
result[0] is "abc"
result[1] is "def"
using split()
String[] words = name.trim().split(" ")
if(words.length >= 2) {
String twoWordsName = words[0] + " " + words[1]
textView.setTexttwoWordsName;
}
To get each of the words In a string
You can use string tokenizer
String sentence = "This is a sentence";
StringTokenizer t = new StringTokenizer(sentence);
String word ="";
while(t.hasMoreTokens())
{
word = t.nextToken();
System.out.println(word);
}
package stringsplit;
public class StringSplit {
public static void main(String[] args) {
String s = "hello world we are anonymous ";
String[] s3 = s.split("\\s",2);
for(String temp:s3){
System.out.println(temp);
}
}
}
O/P:
hello
world we are anonymous
The above code splits my string into two parts after 1 space character
is encountered by compiler.I then introduced '\\s+' so as to split after
2 space characters to get
o/p:
hello world
we are anonymous
But it didn't work.Thanks for you guidance in advanced.
According javadoc String split(regex) and split(regex, limit) work like expected. Depending on result you're trying to achieve you can use something of these below:
String s = "hello world we are anonymous";
String[] s1 = s.split("\\s",2); //result is ["Hello", " world we are anonymous"]
String[] s2 = s.split("\\s+",2); //result is ["Hello", "world we are anonymous"]
String[] s3 = s.split("\\s+",3); //result is ["Hello", "world", "we are anonymous"]
String[] s4 = s.split("\\s+"); //result is ["Hello", "world", "we", "are", "anonymous"]
You can solve your problem using String::indexof :
String s = "hello world we are anonymous ";
s = s.replaceAll("\\s+", " ").trim();//----------------------------------------------(0)
String s1 = s.substring(0, s.indexOf(" ", s.indexOf(" ") + 1));//--------------------(1)
String s2 = s.substring(s.indexOf(" ", s.indexOf(" ") + 1) + 1, s.length() - 1);//---(2)
(0)-Just to make sure that you don't have multiples spaces between the words
(1)-Get the first part from 0 to the second space
(2)-Get the second part from the second space to the end of the string
Output
hello world
we are anonymous
Read the Split doc, "The limit parameter controls the number of times the pattern is applied", so you can't with achieve it with split.
So if you want to split after 2 spaces, you have to write:
String s = "hello world we are anonymous ";
int firstSpace = s.indexOf(' ')+1;
int secondSpace = s.indexOf(' ', firstSpace)+1;
String part1 = s.substring(0, secondSpace);
String part2 = s.substring(secondSpace, s.length());
System.out.println(part1); // return "hello world"
System.out.println(part2); // return "we are anonymous "
I am attempting to write a program that reverses a string's order, even the punctuation. But when my backwards string prints. The punctuation mark at the end of the last word stays at the end of the word instead of being treated as an individual character.
How can I split the end punctuation mark from the last word so I can move it around?
For example:
When I type in : Hello my name is jason!
I want: !jason is name my Hello
instead I get: jason! is name my Hello
import java.util.*;
class Ideone
{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String input = userInput.nextLine();
String[] sentence= input.split(" ");
String backwards = "";
for (int i = sentence.length - 1; i >= 0; i--) {
backwards += sentence[i] + " ";
}
System.out.print(input + "\n");
System.out.print(backwards);
}
}
Manually rearranging Strings tends to become complicated in no time. It's usually better (if possible) to code what you want to do, not how you want to do it.
String input = "Hello my name is jason! Nice to meet you. What's your name?";
// this is *what* you want to do, part 1:
// split the input at each ' ', '.', '?' and '!', keep delimiter tokens
StringTokenizer st = new StringTokenizer(input, " .?!", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
String token = st.nextToken();
// *what* you want to do, part 2:
// add each token to the start of the string
sb.insert(0, token);
}
String backwards = sb.toString();
System.out.print(input + "\n");
System.out.print(backwards);
Output:
Hello my name is jason! Nice to meet you. What's your name?
?name your What's .you meet to Nice !jason is name my Hello
This will be a lot easier to understand for the next person working on that piece of code, or your future self.
This assumes that you want to move every punctuation char. If you only want the one at the end of the input string, you'd have to cut it off the input, do the reordering, and finally place it at the start of the string:
String punctuation = "";
String input = "Hello my name is jason! Nice to meet you. What's your name?";
System.out.print(input + "\n");
if(input.substring(input.length() -1).matches("[.!?]")) {
punctuation = input.substring(input.length() -1);
input = input.substring(0, input.length() -1);
}
StringTokenizer st = new StringTokenizer(input, " ", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
sb.insert(0, st.nextToken());
}
sb.insert(0, punctuation);
System.out.print(sb);
Output:
Hello my name is jason! Nice to meet you. What's your name?
?name your What's you. meet to Nice jason! is name my Hello
Like the other answers, need to separate out the punctuation first, and then reorder the words and finally place the punctuation at the beginning.
You could take advantage of String.join() and Collections.reverse(), String.endsWith() for a simpler answer...
String input = "Hello my name is jason!";
String punctuation = "";
if (input.endsWith("?") || input.endsWith("!")) {
punctuation = input.substring(input.length() - 1, input.length());
input = input.substring(0, input.length() - 1);
}
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String reordered = punctuation + String.join(" ", words);
System.out.println(reordered);
The below code should work for you
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceSample {
public static void main(String[] args) {
String originalString = "TestStr?";
String updatedString = "";
String regex = "end\\p{Punct}+|\\p{Punct}+$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(originalString);
while (matcher.find()) {
int start = matcher.start();
updatedString = matcher.group() + originalString.substring(0, start);<br>
}
System.out.println("Original -->" + originalString + "\nReplaced -->" + updatedString);
}
}
You need to follow the below steps:
(1) Check for the ! character in the input
(2) If input contains ! then prefix it to the empty output string variable
(3) If input does not contain ! then create empty output string variable
(4) Split the input string and iterate in reverse order (you are already doing this)
You can refer the below code:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String originalInput = userInput.nextLine();
String backwards = "";
String input = originalInput;
//Define your punctuation chars into an array
char[] punctuationChars = {'!', '?' , '.'};
String backwards = "";
//Remove ! from the input
for(int i=0;i<punctuationChars.length;i++) {
if(input.charAt(input.length()-1) == punctuationChars[i]) {
input = input.substring(0, input.length()-1);
backwards = punctuationChars[i]+"";
break;
}
}
String[] sentence= input.split(" ");
for (int i = sentence.length - 1; i >= 0; i--) {
backwards += sentence[i] + " ";
}
System.out.print(originalInput + "\n");
System.out.print(input + "\n");
System.out.print(backwards);
}
Don't split by spaces; split by word boundaries. Then you don't need to care about punctuation or even putting spaces back, because you just reverse them too!
And it's only 1 line:
Arrays.stream(input.split("\\b"))
.reduce((a, b) -> b + a)
.ifPresent(System.out::println);
See live demo.
I want to prepend "\n" to the last word of the string
for example
Hello friends 123
Here i want to add "\n" just before the word "123"
I tried below code but having no idea what to do now
String sentence = "I am Mahesh 123"
String[] parts = sentence.split(" ");
String lastWord = "\n" + parts[parts.length - 1];
Try this
String sentence = "Hello friends 123456";
String[] parts = sentence.split(" ");
parts[parts.length - 1] = "\n" + parts[parts.length - 1];
StringBuilder builder = new StringBuilder();
for (String part : parts) {
builder.append(part);
builder.append(" ");
}
System.out.println(builder.toString());
Output will be :~
Hello friends
123456
Try the below code...it will work
parts[parts.length]=parts[parts.length-1];
parts[parts.length-1]="\n";
Please try this.
String sentence = "I am Mahesh 123";
String[] parts = sentence.split(" ");
String string="";
for (int i =0;i<parts.length;i++)
{
if (i==parts.length-1)
{
string = string+"\n"+parts[i];
}
else
string = string+" "+parts[i];
}
Toast.makeText(Help.this, string, Toast.LENGTH_SHORT).show();
You want to add a break/new line at the end of your string.
You can find the space via lastIndexOf(), this will give you the int of where the space is located in the String sentence.
You can use this small example here:
public class Main {
public static void main(String[] args) {
String sentence = "I am Mahesh 123";
int locationOfLastSpace = sentence.lastIndexOf(' ');
String result = sentence.substring(0, locationOfLastSpace) //before the last word
+ "\n"
+ sentence.substring(locationOfLastSpace).trim(); //the last word, trim just removes the spaces
System.out.println(result);
}
}
Note that StringBuilder is not used because since Java 1.6 the compiler will create s StringBuilder for you