Split sentence by words count in Java - java

How can I split a sentence into two groups with equal number of words?
Sentence(odd words count) :
This is a sample sentence
Output: part[0] = "This is a "
part[1] = "sample sentence"
Sentence(even words count) :
This is a sample sentence two
Output: part[0] = "This is a "
part[1] = "sample sentence two"
I tried to split the whole sentence into words, getting the index of ((total number of spaces / 2) + 1)th empty space and apply substring. But it is quite messy and I was unable to get the desired result.

Pretty simple solution using Java8
String[] splitted = test.split(" ");
int size = splitted.length;
int middle = (size / 2) + (size % 2);
String output1 = Stream.of(splitted).limit(middle).collect(Collectors.joining(" "));
String output2 = Stream.of(splitted).skip(middle).collect(Collectors.joining(" "));
System.out.println(output1);
System.out.println(output2);
Output on the 2 test strings is:
This is a
sample sentence
This is a
sample sentence two

String sentence ="This is a simple sentence";
String[] words = sentence.split(" ");
double arrayCount=2;
double firstSentenceLength = Math.ceil(words.length/arrayCount);
String[] sentences = new String[arrayCount];
String first="";
String second="";
for(int i=0; i < words.length; i++){
if(i<firstSentenceLength){
first+=words[i]+ " ";
}else{
second+=words[i]+ " ";
}
}
sentences[0]=first;
sentences[1]=second;
I hope this help you.

String sentence = "This is a sample sentence";
String[] words = sentence.split(" +"); // Split words by spaces
int count = (int) ((words.length / 2.0) + 0.5); // Number of words in part[0]
String[] part = new String[2];
Arrays.fill(part, ""); // Initialize to empty strings
for (int i = 0; i < words.length; i++) {
if (i < count) { // First half of the words go into part[0]
part[0] += words[i] + " ";
} else { // Next half go into part[1]
part[1] += words[i] + " ";
}
}
part[1] = part[1].trim(); // Since there will be extra space at end of part[1]

Related

How to display split strings in JOptionpane by user's split size

Hi how can I display my Split Strings in JOptionPane? My window keeps printing/showing my strings 1 by 1 , I want them to print/show given my user's split size
String letters, splitSize;
letters = JOptionPane.showInputDialog("Enter String: ");
final int numInLetters = letters.length();
splitSize = JOptionPane.showInputDialog("Enter Split Size");
int sizeSplit = Integer.parseInt(splitSize);
if (numInLetters % sizeSplit == 0) {
JOptionPane.showMessageDialog(null, "The Given String is" + letters);
JOptionPane.showMessageDialog(null, "The Split String are: ");
String []in_array;
in_array = letters.split("");
for (int i = 1; i <= in_array.length; i++) {
//what alternative way to show my split string here given by user's split size
JOptionPane.showMessageDialog(null, in_array[i-1]);
if (i % sizeSplit == 0) {
JOptionPane.showMessageDialog(null, "");
I'm not exactly sure what you're trying to accomplish, but I think this might be what you want:
String letters = JOptionPane.showInputDialog("Enter String: ");
String splitSize = JOptionPane.showInputDialog("Enter Split Size");
int sizeSplit = Integer.parseInt(splitSize);
List<String> list = new ArrayList<>();
int idx = 0;
while (idx < letters.length()) {
int toIdx = Math.min(idx + sizeSplit, letters.length());
list.add(letters.substring(idx, toIdx));
idx = toIdx;
}
JOptionPane.showMessageDialog(null, "The Split String are: " + System.lineSeparator() + String.join(System.lineSeparator(), list));

how to seperate last and remaining all words in java?

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

How to prepend "\n" to the last word of String?

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

Counting number of time the articles "a","an" are being used in a text file

I'm trying to make a program that count the number of words, lines, sentences, and also the number of articles 'a', 'and','the'.
So far I got the words, lines, sentences. But I have no idea who I am going to count the articles. How can a program make the difference between 'a' and 'and'.
This my code so far.
public static void main(String[]args) throws FileNotFoundException, IOException
{
FileInputStream file= new FileInputStream("C:\\Users\\nlstudent\\Downloads\\text.txt");
Scanner sfile = new Scanner(new File("C:\\Users\\nlstudent\\Downloads\\text.txt"));
int ch,sentence=0,words = 0,chars = 0,lines = 0;
while((ch=file.read())!=-1)
{
if(ch=='?'||ch=='!'|| ch=='.')
sentence++;
}
while(sfile.hasNextLine()) {
lines++;
String line = sfile.nextLine();
chars += line.length();
words += new StringTokenizer(line, " ,").countTokens();
}
System.out.println("Number of words: " + words);
System.out.println("Number of sentence: " + sentence);
System.out.println("Number of lines: " + lines);
System.out.println("Number of characters: " + chars);
}
}
How can a program make the difference between 'a' and 'and'.
You can use regex for this:
String input = "A and Andy then the are a";
Matcher m = Pattern.compile("(?i)\\b((a)|(an)|(and)|(the))\\b").matcher(input);
int count = 0;
while(m.find()){
count++;
}
//count == 4
'\b' is a word boundary, '|' is OR, '(?i)' — ignore case flag. All list of patterns you can find here and probably you should learn about regex.
The tokenizer will split each line into tokens. You can evaluate each token (a whole word) to see if it matches a string you expect. Here is an example to count a, and, the.
int a = 0, and = 0, the = 0, forCount = 0;
while (sfile.hasNextLine()) {
lines++;
String line = sfile.nextLine();
chars += line.length();
StringTokenizer tokenizer = new StringTokenizer(line, " ,");
words += tokenizer.countTokens();
while (tokenizer.hasMoreTokens()) {
String element = (String) tokenizer.nextElement();
if ("a".equals(element)) {
a++;
} else if ("and".equals(element)) {
and++;
} else if ("for".equals(element)) {
forCount++;
} else if ("the".equals(element)) {
the++;
}
}
}

Java - Mix up letters

Can someone give me an example of how to split Strings before you scramble the letters
I can scramble the words but it changes the length of the words too
Example:
input : Hello my name is Jon
output: e imanoJs my nlolHe
But it should be like this
input : Hello my name is Jon
output: Hlelo my nmae is Jon
so the first and last letter should stay in place
here is my code so far
public class MixUp{
public static void main(String[] args){
String cards="Hello my Name is Jon, nice to meet you";
System.out.println("Input String = " + cards);
cards = shuffle(cards);
System.out.println("Shuffled String = " + cards);
}
static String shuffle(String cards){
if (cards.length()<=1)
return cards;
int split=cards.length()/2;
String temp1=shuffle(cards.substring(0,split));
String temp2=shuffle(cards.substring(split));
if (Math.random() > 0.5)
return temp1 + temp2;
else
return temp2 + temp1;
}
}
Notes
Use Collections.shuffle() in combination with List.subList() so that the first and last letters are not moved.
Convert to and from primitive array so that Collections.shuffle() can be used
Code
private static String shuffle(String sentence) {
String[] words = sentence.split("\\s+");
StringBuilder builder = new StringBuilder();
for (String word : words) {
List<Character> letters = new ArrayList<Character>();
for (char letter : word.toCharArray()) {
letters.add(letter);
}
if (letters.size() > 2) {
Collections.shuffle(letters.subList(1, letters.size() - 1));
}
for (char letter : letters) {
builder.append(letter);
}
builder.append(" ");
}
return builder.toString();
}
inputString.split(" ") will split on spaces and return an array of Strings. Create a new array, iterate through the first split array and shuffle each string and add the shuffled string to the new array.
String cards="Hello my Name is Jon, nice to meet you";
System.out.println("Input String = " + cards);
String[] splt = cards.split(" ");
String[] shuffled = new String[splt.length];
for (int iter = 0; iter < splt.length; iter ++){
shuffled[iter] = shuffle(splt[iter]);
}
// Now join the array
EDIT Better yet use a StringBuilder
String cards="Hello my Name is Jon, nice to meet you";
System.out.println("Input String = " + cards);
String[] splt = cards.split(" ");
StringBuilder sb = new StringBuilder();
for (int iter = 0; iter < shuffled.length; iter ++){
sb.append(shuffle(splt[iter]) + " ");
}
String shuffled = sb.toString();
You should split the sentence into words and then scramble the words:
String[] words = sentence.split(" ");
for(String word : words)
word = shuffle(word);
Then concat the word together to a sentence.

Categories

Resources