Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
can you give me some pointers as of how can I find the most frequent word in an String? I cannot use Maps, lists or so on. I should only achieve this by for's and if's and some in-build methods.
Split String and save to array, sort the array, iterate over the sorted array and count frequency of same strings updating the maximal count. Example:
public static void main(String[] args) {
String myStr = "how can I find the most frequent word in an string how can I find how how how string";
String[] splited = myStr.split(" ");
Arrays.sort(splited);
System.out.println(Arrays.toString(splited));
int max = 0;
int count= 1;
String word = splited[0];
String curr = splited[0];
for(int i = 1; i<splited.length; i++){
if(splited[i].equals(curr)){
count++;
}
else{
count =1;
curr = splited[i];
}
if(max<count){
max = count;
word = splited[i];
}
}
System.out.println(max + " x " + word);
}
Sample idea (there are thousand ways to solve this):
1: A B B C B (< String with words, seperated by blanks)
'A' is your start position
2: count the A (1) and save the pos of A (0). You always iterate from pos until the end of the String.
3: continue counting until you iterated over the entire String. When you reached the end of the String save the count by assigning it to another variable (e.g. oldCount).
4: move on to the next word and start counting B's (new position = 1). You are about to count 3 B's. If newer count > older count replace the older count.
5: count the next word and update the position to your current position, which is 3. (which is the last position of the String).
6: you are not gonna update the counter, B is the most used word in the String.
For the purists - just loops and String.
private String mostFrequentWord(String words) {
// Where my current word starts.
int wordStart = 0;
// How many I counted.
int wordCount = 0;
// The currently most frequent.
String word = "";
for (int wordEnd = wordStart; wordEnd < words.length(); wordEnd++) {
// Is this the end of a word?
if (wordEnd > words.length() || words.charAt(wordEnd) == ' ') {
// We have a word! How many times does it occur?
String thisWord = words.substring(wordStart, wordEnd);
// How many times this word occurs.
int thisWordCount = 0;
// Current start of search.
int search = -1;
// Count them.
while ((search = words.indexOf(thisWord, search + 1)) >= 0) {
thisWordCount += 1;
}
// Is it longer?
if (thisWordCount > wordCount) {
// Keep track.
word = thisWord;
wordCount = thisWordCount;
}
// Move start to the next word.
wordStart = wordEnd + 1;
}
}
return word;
}
private void test() {
String words = "Now is the time for all good men to come to the aid of the party";
System.out.println("Most frequent word in \"" + words + "\" is " + mostFrequentWord(words));
}
public static void main(String...strings) {
String para = "Paris in the the spring.Not that that is related.Why are you laughing? Are my my regular expressions THAT bad??";
String[] words = para.split("\\s+");
int finalCount = 0;
int tempCount = 0;
String mostlyUsedWord = null;
for (String word: words) {
tempCount = 0;
for (String w: words) {
if (word.equalsIgnoreCase(w)) {
tempCount++;
}
}
if (tempCount >= finalCount) {
finalCount = tempCount;
mostlyUsedWord = word;
}
}
System.out.println("mostlyUsedWord:: = " + mostlyUsedWord + " ,count:: = " + finalCount);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Input a string which contains some palindrome substrings. Find out the position of palindrome substrings if exist and replace it by *. (For example if input string is βbob has a radar planeβ then it should convert in β** has a ***** planeβ.
My code is given below.
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}
There is a simpler, more efficient way of finding palindromes in Java. I'll explain the steps to implementing it.
first, after getting your input 'sen', you can use the split method of the String class to seperate each word.
sen = in.nextLine();
String[] splitted = s.split(" "); // seperates the string when there is a whitespace and stores the resulting words in an array
After you've got the words in an array, you can check each word and see if its a palindrome. To do so, you can read the word front to back and back to front and compare the result.
If u find a palindrome, store its index (position in the 'splitted' array). After you've gone through all the words in the 'splitted' array, you can then print out the appropriate number of *'s based on the length of the word.
The split() will loose double spaces and punctuation in source string and make a lot of useless objects in memory. This is more correct solution. IMHO
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am solving a problem on leetcode.Here is the question link
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Below is my solution which is not passing some test-cases:
abcabcbb -- not correct
pwwkew -- correct
bbbbb -- not correct
Any help would be thankful:)
And also I am a newbie here so you can suggest me about my problem statement.
class Solution {
public int lengthOfLongestSubstring(String s) {
int i,max=0;
List<Character> list = new ArrayList<>();
String x = "";
for(i=0;i<s.length();i++)
{
if(!list.contains(s.charAt(i)))
{
x += s.charAt(i);
list.add(s.charAt(i));
System.out.println(x);
}
else
{
if(x != null && x.length() > max)
{
max = x.length();
System.out.println(max);
x = "";
list.clear();
System.out.println("x : "+ x);
System.out.println("list : "+ list);
}
// else
// {
// list.add(s.charAt(i));
// x += s.charAt(i);
// System.out.println("x in else : "+ x);
// System.out.println("list in else : "+ list);
// }
list.add(s.charAt(i));
x += s.charAt(i);
System.out.println("x in else : "+ x);
System.out.println("list in else : "+ list);
}
}
return max;
}
}
Sometimes it's helpful to remain in the problem domain as much as possible. This approach creates a solution before any thought of coding. This approach leaves us with a set of minimally complex logical operations which then require implementation.
First our initial condition. Columns should be clear: Input (always same), Current (the current substring without repeating characters), Answer (the current answer in String form) and Logic (what logic is applied for this step:
So first iteration starts the same as rest : get next character in Input. Check if it is in the Current substring and since it is not add to Current. Here we also ask the question: Is Answer shorter than Current and if so set Answer to Current.
Note in the Logic column we are developing operations which we'll need to implement in the solution.
Repeat for second character input (no new operations):
And again for third - (no new operations):
Ok now we find next CH in the current substring so we need a new operation: 'Remove chars in current up to but not including CH. Note that "add CH to current" is done in this case as well. Note also some new logic (answer was as long or longer than current so "Do Nothing").
And finish things out - no new operations.
So now we reach the end of input and simply ask the question "How long is the Answer" and that is the result.
So now looking at the Logic column we see operations to perform:
// Initial condition
String answer = "";
String current = "";
Let's work completely in Strings to keep things simple - optimization can come later..
Let's define the "next CH (nextChar)" operation:
// Get the ith character (0-based) from 's' as a String.
private static String nextChar(String s, int i) {}
We'll need an operation which "checks if 'Current contains CH'":
// Does the 'current' String contain the 'nextChar' String?
private static boolean currentContainsCh(String current, String nextChar) {}
We'll need to check if current Answer is shorter than Current:
// True if the 'answer' String is short in length than the 'current' string.
private static boolean isAnswerShorterThanCurrent(String current, String answer) {}
And the ability to append the nextChar to Current:
// Append the 'nextChar' to the 'current' String and return the String.
private static String addChToCurrent(String current, String nextChar) {}
And finally the ability to remove all characters up to but not including current char in Current:
// #return a String which has all characters removed from 'current' up to but not including 'ch'
private static String removeUpToChar(String current, String ch) {}
So putting it all together (essentially still in the problem domain since we haven't implemented any operations but just projected the problem into structure):
public int lengthOfLongestSubstring(String s) {
String answer = "";
String current = "";
for (int i = 0; i < s.length(); i++) {
String nextChar = nextChar(s,i);
if (currentContainsCh(current, nextChar)) {
current = removeUpToChar(current, nextChar);
}
current = addChToCurrent(current,nextChar);
if (isAnswerShorterThanCurrent(current,answer)) {
answer = new String(current);
}
}
return answer.length();
}
And now implementing the "operations" becomes easier (and fun) since they are isolated and not complex. This is left for you. When implemented it passes the problem.
The next logical step after verifying correctness is to consider optimizations - if needed.
Although the pictures in answer by Andy are useful and mostly correct, the code is sub-optimal.
The code in the question, as well as in both current answers, builds a lot of substrings, using string concatenation. That is detrimental to performance.
Here is an O(n) solution that doesn't build any substrings:
public static int lengthOfLongestSubstring(String s) {
Map<Character, Integer> lastPos = new HashMap<>();
int start = 0, maxLen = 0, i = 0;
for (; i < s.length(); i++) {
Integer pos = lastPos.put(s.charAt(i), i);
if (pos != null && pos >= start) {
if (i > start + maxLen)
maxLen = i - start;
start = pos + 1;
}
}
return (i > start + maxLen ? i - start : maxLen);
}
This works by remembering the last position of each character, so the potential longest substring's starting position can be adjusted to start right after the previous position of a repeating character.
Since HashMap.put(...) is O(1) (amortized), the solution is O(n).
Since it would be nice to see the substring, we can easily modify the code to return the (first1) longest substring:
public static String longestSubstring(String s) {
Map<Character, Integer> lastPos = new HashMap<>();
int start = 0, maxStart = 0, maxLen = 0, i = 0;
for (; i < s.length(); i++) {
Integer pos = lastPos.put(s.charAt(i), i);
if (pos != null && pos >= start) {
if (i > start + maxLen) {
maxStart = start;
maxLen = i - start;
}
start = pos + 1;
}
}
return (i > start + maxLen ? s.substring(start) : s.substring(maxStart, maxStart + maxLen));
}
1) To return the last of multiple longest substrings, change both i > to i >=
The above solutions cannot handle strings with Unicode characters from the supplemental planes, e.g. emoji characters.
Emoji's such as π and π are stored as "\uD83D\uDE00" and "\uD83D\uDE01", so the char value '\uD83D' will be seen as a repeating character.
To make it correctly handle all Unicode characters, we need to change it to:
public static String longestSubstring(String s) {
Map<Integer, Integer> lastPos = new HashMap<>();
int start = 0, maxStart = 0, maxLen = 0, i = 0;
for (int cp; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
Integer pos = lastPos.put(cp, i);
if (pos != null && pos >= start) {
if (i > start + maxLen) {
maxStart = start;
maxLen = i - start;
}
start = pos + Character.charCount(cp);
}
}
return (i > start + maxLen ? s.substring(start) : s.substring(maxStart, maxStart + maxLen));
}
Test
for (String s : new String[] { "abcabcbb", "pwwkew", "bbbbb", "aab", "abba", "xabycdxefghy", "aXbXcdXefgXh", "ππππππ" }) {
String substr = longestSubstring(s);
System.out.printf("%s: %s (%d)%n", s, substr, substr.length());
}
Output
abcabcbb: abc (3)
pwwkew: wke (3)
bbbbb: b (1)
aab: ab (2)
abba: ab (2)
xabycdxefghy: abycdxefgh (10)
aXbXcdXefgXh: cdXefg (6)
ππππππ: πππ (6)
Edit: To those who downvote me, this question is difference from the duplicate question which you guy linked. The other question is about returning the indexes. However, for my case, I do not need the index. I just want to check whether there is duplicate.
This is my code:
String word = "ABCDE<br>XYZABC";
String[] keywords = word.split("<br>");
for (int index = 0; index < keywords.length; index++) {
if (keywords[index].toLowerCase().contains(word.toLowerCase())) {
if (index != (keywords.length - 1)) {
endText = keywords[index];
definition.setText(endText);
}
}
My problem is, if the keywords is "ABC", then the string endText will only show "ABCDE". However, "XYZABC" contains "ABC" as well. How to check if the string has multiple occurrence? I would like to make the definition textview become definition.setText(endText + "More"); if there is multiple occurrence.
I tried this. The code is working, but it is making my app very slow. I guess the reason is because I got the String word through textwatcher.
String[] keywords = word.split("<br>");
for (int index = 0; index < keywords.length; index++) {
if (keywords[index].toLowerCase().contains(word.toLowerCase())) {
if (index != (keywords.length - 1)) {
int i = 0;
Pattern p = Pattern.compile(search.toLowerCase());
Matcher m = p.matcher( word.toLowerCase() );
while (m.find()) {
i++;
}
if (i > 1) {
endText = keywords[index];
definition.setText(endText + " More");
} else {
endText = keywords[index];
definition.setText(endText);
}
}
}
}
Is there any faster way?
It's a little hard for me to understand your question, but it sounds like:
You have some string (e.g. "ABCDE<br>XYZABC"). You also have some target text (e.g. "ABC"). You want to split that string on a delimiter (e.g. "<br>", and then:
If exactly one substring contains the target, display that substring.
If more than one substring contains the target, display the last substring that contains it plus the suffix "More"
In your posted code, the performance is really slow because of the Pattern.compile() call. Re-compiling the Pattern on every loop iteration is very costly. Luckily, there's no need for regular expressions here, so you can avoid that problem entirely.
String search = "ABC".toLowerCase();
String word = "ABCDE<br>XYZABC";
String[] keywords = word.split("<br>");
int count = 0;
for (String keyword : keywords) {
if (keyword.toLowerCase().contains(search)) {
++count;
endText = keyword;
}
}
if (count > 1) {
definition.setText(endText + " More");
}
else if (count == 1) {
definition.setText(endText);
}
You are doing it correctly but you are doing unnecessary check which is if (index != (keywords.length - 1)). This will ignore if there is match in the last keywords array element. Not sure is that a part of your requirement.
To enhance performance when you found the match in second place break the loop. You don't need to check anymore.
public static void main(String[] args) {
String word = "ABCDE<br>XYZABC";
String pattern = "ABC";
String[] keywords = word.split("<br>");
String endText = "";
int count = 0;
for (int index = 0; index < keywords.length; index++) {
if (keywords[index].toLowerCase().contains(pattern.toLowerCase())) {
//If you come into this part mean found a match.
if(count == 1) {
// When you found the second match it will break to loop. No need to check anymore
// keep the first found String and append the more part to it
endText += " more";
break;
}
endText = keywords[index];
count++;
}
}
System.out.println(endText);
}
This will print ABCDE more
Hi You have to use your condition statement like this
if (word.toLowerCase().contains(keywords[index].toLowerCase()))
You can use this:
String word = "ABCDE<br>XYZABC";
String[] keywords = word.split("<br>");
for (int i = 0; i < keywords.length - 1; i++) {
int c = 0;
Pattern p = Pattern.compile(keywords[i].toLowerCase());
Matcher m = p.matcher(word.toLowerCase());
while (m.find()) {
c++;
}
if (c > 1) {
definition.setText(keywords[i] + " More");
} else {
definition.setText(keywords[i]);
}
}
But like what I mentioned in comment, there is no double occurrence in word "ABCDE<br>XYZABC" when you want to split it by <br>.
But if you use the word "ABCDE<br>XYZABCDE" there is two occurrence of word "ABCDE"
void test() {
String word = "ABCDE<br>XYZABC";
String sequence = "ABC";
if(word.replaceFirst(sequence,"{---}").contains(sequence)){
int startIndex = word.indexOf(sequence);
int endIndex = word.indexOf("<br>");
Log.v("test",word.substring(startIndex,endIndex)+" More");
}
else{
//your code
}
}
Try this
I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:
public void bigesttstring(String str){
String[] wordsArray=str.split(" ");
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
}
}
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:
int count=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
count++;
}
}
and for display other longest strings i have this code:
int k=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
k++;
}
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
other[o]=wordsArray[i];
o++;
}
}
I allowed to use this functions:
char char At(int i);
int ComoareTo(String another string);
boolean endsWith(String suffix);
int indexof();
int indexof(String str);
String substring();
char[] toCharArray();
String lowercase();
And want another code like this for shortest strings.
You have written
if(wordsArray[i].length()>maxsize)
For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4.
Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be
if(wordsArray[i].length()>=maxsize)
you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.
You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.
package OtherPeoplesCode;
public class string {
public static void main(String[] args) {
bigeststring("wall hall to wall hall fall be");
}
public static void bigeststring(String str){
String[] wordsArray=str.split(" ");
String[] biggestWordsArray = new String[wordsArray.length];
int x = 0;
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
for(int y = 0; y <= biggestWordsArray.length -1; y++){
biggestWordsArray[y] = "";
}
}
else if(maxsize==wordsArray[i].length()){
biggestWordsArray[x] = wordsArray[i];
x++;
}
}
if(biggestWordsArray[0].equals("")){
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
else if(!(biggestWordsArray[0].equals(""))){
System.out.println("TIE!");
for(int y = 0; y <= biggestWordsArray.length -1; y++){
if(!(biggestWordsArray[y].equals(""))){
System.out.print("Word #" + y + " is ");
System.out.println(biggestWordsArray[y]);
}
}
}
}
}
EDIT: This is the working code, sorry about the delay.
Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.
One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):
loop through the list of words, and find out the length of the longest word and number of words with such length
Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want
in psuedo code:
String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
if word is longer then maxLen {
maxLen = word's length
maxLenOccurence = 1;
}
else if word's length is equals to maxLen {
maxLenOccurence ++
}
}
// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
else if word's length is equals to maxLen {
for i = 0 to maxLenWordList length {
if (maxLenWordList[i] == word)
break
if (maxLenWordList[i] == null
maxLenWordList[i] = word
}
}
//4
foreach maxLenWord in maxLenWordList {
count = 0
foreach word in wordList {
if maxLenWord == word
count ++
}
display "Max sized word is "+ maxLenWord + " with size " + count
}
Another way doesn't involve other data structure is:
Have the word list
Sort the word list first by length then by the literal value
First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Also you can use this;
String[] allLongestStrings(String[] inputArray) {
List<String> list = new ArrayList<String>();
int max = 0;
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n > max) {
max = n;
}
}
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n == max) {
list.add(s.toString());
}
}
return list.toArray(new String[list.size()]);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How can I break a line automatically into many lines without cutting off words? And the length for each new line will be around 4 words? I have many sentences thus I cannot use \n
e.g:
If I were you I would go to the cinema with her
becomes:
If I were you
I would go to
the cinema with her
Hope see your help soon. Thanks!
I would imagine, based on what you put although I'm not sure you're considering all possible cases, a way to get the specific answer you're looking for while taking a few things for granted and not directly relying on "\n" would be...
String s = "If I were you I would go to the cinema with her";
String[] strings = s.split(" ");
for(int i = 0; i < strings.length; ++i) {
if(i % 4 == 0) {
System.out.println();
}
System.out.print(strings[i] + " ");
}
Alternatively you might consider something like this, which would handle a max width of your text field as opposed to a set number of words since some words may be very long and cause a situation which you're trying to avoid...
int MAX = 20;
int length = 0;
String s = "If I were you I would go to the cinema with her.";
String[] strings = s.split(" ");
for(int i = 0; i < strings.length; ++i) {
if((length + strings[i].length()) > MAX ) {
System.out.println();
length = 0;
}
System.out.print(strings[i] + " ");
length += strings[i].length() + 1;
}
Edit:
I did as you requested. This is what I get from the MAX option...
If I were you I
would go to the
cinema with her and
abc xyz
And this is what I get for the regular...
If I were you
I would go to
the cinema with her
and abc xyz
Not sure what's happening there, but I will say I jumped the shark on my answer. You've tagged Android and you and I both know System.out.println() is a no-no in that environment, at least if you expect to see any results. Sorry about that.
you need to count the number of spaces in a for loop here is a code to demonstrate it. please change the variables according to your application
String tv2 = tv.getText().toString(); // take a string textVIew, you can make it editView
StringBuilder sb = new StringBuilder(tv2); // add the string to stringBuilder
int howManySpaces = 0; // this for counting the spaces.
for (int i = 0; i < tv2.length(); i++)
{
if (tv2.charAt(i) == ' ') //if space found add one to howManySpaces
{
howManySpaces += 1;
Log.d("HMS", String.valueOf(howManySpaces));
}
if (howManySpaces == 4) // if howManySpaces == 4 break it to new line
{
sb.replace(i, i+1, "\n");
howManySpaces = 0;
}
}
tvNew.setText(sb.toString()); // add to the new textView the result after breaking.
I just tried it right now, with same sentences it gave me the desired result.
feel free to ask me if you didnt understand any part.
I have tried the following code, it worked fine for me, please try this and kindly let me if you have any trouble on this
// Calling the SentenceBreaker method which helps the String to split.
sentenceBreaker("If I were you I would go to the cinema with her");
// Method which spilts the Sentence
private void sentenceBreaker(int noOfWords,String inputSentence){
boolean previousCharWhiteSpace = true; // just a flag
boolean initialFlag =false;
int wordCount = 0;
int i,count =0;
for (i = 0; i < inputSentence.length(); i++) {
if (inputSentence.charAt(i) == ' ' && !previousCharWhiteSpace) {
wordCount++;
previousCharWhiteSpace = true;
if (wordCount == noOfWords) {
if(count == 0){
inputSentence = inputSentence.substring(0,wordCount)
+ "\n"
+ inputSentence.substring(wordCount,
inputSentence.length());
wordCount = 0;
count=i;
}
else{
inputSentence = inputSentence.substring(count, i)
+ "\n"
+ inputSentence.substring(i,
inputSentence.length());
wordCount = 0;
count=i;
}
}
} else if (!(inputSentence.charAt(i) == ' ')) {
previousCharWhiteSpace = false;
}
}
/*
* the for loop increments the word count if a space is encountered
* between words,for multiple spaces between words it wont update the
* counter-hence the use of the boolean flag.
*/
if (!(inputSentence.charAt(i - 1) == ' ')) {
wordCount++;
}
// just to make sure that we count the last word in the sentence as well
System.out.println("No of words-" + wordCount);
System.out.println("Sentence" + inputSentence);
}
/* Output */
Sentence If I were you
I would go to
the cinema with her**
As Per Your Requirement..Following logic will be works fine..Please Use it
String stT="If I were you I would go to the cinema with her";
String[] sT=stT.split(" ");
StringBuffer sb=new StringBuffer();
for(int i=0;i<sT.length;i++)
{
if(i%4==3)
sb.append(sT[i]+"\n");
else
sb.append(sT[i]+" ");
}
System.out.print(sb.toString());