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());
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
So I am trying to fit a String called description into a box. For example:
|This is the description |
|of this card. It is very |
|interesting |
| |
| |
| |
| |
My code does exactly this. However I am afraid I am being very inefficient.
So my question, Is my approach and code effective? or is there any other more convenient way WITHOUT USING LIBRARIES of approaching and coding this problem? I am NOT asking you to re-write my code for me. All I need is someone to verbally explain to me what I could improve on, How I'm approaching the problem incorrectly, what resources I can use to help me etc.
My approach:
Put all the words from the string into an array.
Create an array to contain all the rows that I need to print out.
Insert the words into the rows if they can fit, if not then move onto the next row.
NOTE: If the description is too long then it gets cut short which I don't mind.
So this is my code (I realise that it is very bulky, that is why I feel there is a better way of doing this):
public String[] descriptionFormat(String description)
{
int wordCount = 1; //Int for keeping track words amount in String
for(int i = 0; i < description.length(); i++) //Count the amount of words in the String
{
if(description.charAt(i) == ' ')
{
wordCount++;
}
}
String words[] = new String[wordCount]; //Array of words
String temp = description;
for(int i = 0; i < wordCount; i++) //loop for filling array with words
{
String word = "";
if(temp.indexOf(' ') != -1)
{
word = temp.substring(0,temp.indexOf(' '));
temp = temp.substring(temp.indexOf(' ') + 1);
}
else
{
word = temp.substring(0,temp.length());
}
words[i] = word;
}
String descriptionArray[] = new String[7]; //Array of description rows
for(int i = 0; i < descriptionArray.length; i++) //Fill array with non null values
{
descriptionArray[i] = "";
}
int word = 0; //int to keep track which word we trying to insert
for(int i = 0; i < descriptionArray.length; i++)
{
int index = 0; //index for how much characters we already have in a row
while(word < words.length && words[word].length() < (rowWidth - 3) - index ) //while the word can fit into the row
{
index += words[word].length() + 1;
descriptionArray[i] += words[word] + " ";
word++;
}
}
for(int i = 0; i < descriptionArray.length; i++)
{
descriptionArray[i] = "|" + descriptionArray[i]; //add left border
while(descriptionArray[i].length() < rowWidth - 2) //insert appropriate spaces
{
descriptionArray[i] += " ";
}
descriptionArray[i] = descriptionArray[i] + "|"; //add right border
}
/*
for(int i = 0; i < descriptionArray.length; i++) //print rows for test
{
System.out.println(descriptionArray[i]);
}
*/
return descriptionArray;
}
With regex and printf(), it can be done like this:
static void printColumn(String input, int width) {
String format = "|%-" + width + "s|%n";
Matcher m = Pattern.compile("\\s*+(.{1," + width + "})(?:\\s+|$)").matcher(input);
while (m.find())
System.out.printf(format, m.group(1));
}
Test 1
printColumn("This is the description of this card. It is very interesting", 26);
|This is the description of|
|this card. It is very |
|interesting |
Test 2
printColumn("This is the description of this card.\n" +
"It is very interesting", 26);
|This is the description of|
|this card. |
|It is very interesting |
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);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hello Stack Overflow Community. I developed a simple Java program to detect whether or not a word entered by the user is an Anagram. I do not receive the expected output based on the boolean value. Any ideas or suggestions are appreciated.
Note: This code does not include any methods or class functions that would make this a rather simple solution. Please work with the code below. Thank you!
import javax.swing.*;
public class Anagram
{
public static String word = " ";
public static boolean match = false;
public static void main(String[] args)
{
//Prompt the User for a Word
word = JOptionPane.showInputDialog("Please Enter A Word");
//Break the Word into an Array
String[] anagram = new String[word.length()];
for(int i = 0; i < word.length(); i++)
{
anagram[i] = Character.toString(word.charAt(i));
JOptionPane.showMessageDialog(null, anagram[i]);
}
//Create a duplicate Array
String[] anagram2 = new String[word.length()];
for(int i = word.length() - 1; i >= 0; i--)
{
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
//Do a search on each letter
for (int i = 0; i < anagram.length && i < anagram2.length; i++)
{
if(anagram.length == anagram2.length)
{
if(anagram[i].toLowerCase() == anagram2[i].toLowerCase())
{
match = true;
}
else
{
match = false;
}
}
else
{
JOptionPane.showMessageDialog(null, "There is a mismatch");
match = false;
}
}
//Prompt the user with the result
if(match == true)
{
JOptionPane.showMessageDialog(null, "Your Word is a Anagram!");
}
else if(match == false)
{
JOptionPane.showMessageDialog(null, "Your Word is NOT a Anagram!");
}
}
}
Assuming you mean palindrome:
Your code doesn't actually reverse the String.
for(int i = word.length() - 1; i >= 0; i--) {
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
This copies anagram into anagram2 without reversing it - it does go through it from back to front, but the result will be the same.
You need to do something like
for (int i = 0; i < word.length(); i++) {
anagram2[word.length() - i - 1] = anagram[i];
}
However, there really is no need to create the anagram and anagram2 arrays in the first place, you can just iterate through the String's data itself using charAt.
boolean match = true;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
match = false;
break;
}
}
Side note, you shouldn't declare word and match as static variables, keeping them local in main() will do.
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 8 years ago.
Improve this question
I know I'm not supposed to do this but I am a beginner and I need help on this. I am wondering what I need in each number on the bottom. I am not asking for the code but just help on what to use.
Clarification:
What the problem is asking for is to go through the String one character at a time.
A "valid" word is written backwards in between ? and &
example: valid would be encrypted as ?dilav&
The entire message of encrypted words are also in reverse order.
I hope I made it more clear
Start by thinking how you would solve this in your head.
You would start at the left and look at each character until you found a '?'. Then you would note the letters until you found a '&'. Bingo, first word. Continue until you have all the words.
Now you know how many words you have (answer #2).
Then you need to reverse the letters in each word.
Now print them in the order you found them (answer #3).
Now print them in reverse order - the last word first (answer #4).
Now print the reversed list with spaces between them (answer #5).
Sample code (please try to understand how it works and don't just copy it and hand it in - or your teacher will ask you to explain how it works):
public static void main(final String[] args){
// example provided by Jason via Stackoverflow
String message = "&*#$#?ebyam,&?siht&=asdf???od&failure???&?on?nac&the%%#?uoy&horizon!";
System.out.println("#1: " + message.length());
List<String> words = new ArrayList<String>();
int questionPos = message.indexOf("?");
while(questionPos > -1) {
message = message.substring(questionPos + 1, message.length());
int ampersandPos = message.indexOf("&");
questionPos = message.indexOf("?");
if(ampersandPos > 0 && (ampersandPos < questionPos || questionPos == -1)) {
String word = message.substring(0, ampersandPos);
StringBuilder reversedWord = new StringBuilder();
for(int i = word.length() - 1; i >= 0; i--) {
reversedWord.append(word.charAt(i));
}
words.add(reversedWord.toString());
}
}
System.out.println("#2: " + words.size());
System.out.println("#3:");
for(final String word : words) {
System.out.println(word);
}
System.out.println("#4:");
for(int i = words.size() - 1; i >= 0; i--) {
System.out.println(words.get(i));
}
System.out.print("#5: ");
for(int i = words.size() - 1; i >= 0; i--) {
if(i < words.size() - 1) {
System.out.print(" ");
}
System.out.print(words.get(i));
}
}
(This is not homework)
We have some extra exercices we can do, and i have done some.
But i got stuck in this one...
I need to make a program that given the string "loool" prints "l:1:o:3:l:1".
I have tried a bunch of combinations but i keep getting the same problem:
- I cant make the last repeated letter to get print ( Because with my code the next char needs to be different for a print to occurr).
String str = "loool";
StringBuilder sb = new StringBuilder();
int count = 1;
char before;
before = str.charAt(0);
for (int i = 1;i < str.length();i++) {
if (str.charAt(i) == before) {
count++;
}
else {
sb.append(before + ":" + count);
before = str.charAt(i);
count = 1;
}
}
return sb.toString();
You need to add some logic after your loop has finished, in order to deal with this problem. This logic will probably be very similar to the some of the code that you're using in the else block.