This week's book giveaways are in the Cloud and AI/ML forums. We're giving away four copies each of Cloud Native Patterns and Natural Language Processing and have the authors on-line! See this thread and this one for details.
i'm working on this program. You write in a string, and if there were more than one space in front of, in the middle or at the end of the string, the program will get rid of them, and also will put only one space in between characters. I can get rid of the spaces at the end and beginning, but i cannot figure out how to put spaces in between words. Can anyone help me???
System.out.println("The Original String Was:\""+str+"\""); System.out.println("The Fixed Up String is:\""+NewString+"\"");
str = JOptionPane.showInputDialog("Enter Another String"); } System.out.println("End of Processing"); System.exit(0); }
The Point of the program is to enter a string, usually a really messed up one with too many spaces in front and behind, and the program is supposed to correct this, and evenly space out the words, and get rid of the spaces in front and behind.
You can do achieve this in many ways and one way can be as follows: As you traverse through each character of the string just set a flag which holds whether the last character that you had passed is a space or not. So if the flag is set it means that the previous character that you had passed is a space and hence you need to just skip that space and check for the next character. Proceed using the same logic till you encounter the end of the string. Hope this is clear. You can refer to the below code for reference.
Hope this helps! - John
Do not let what you cannot do interfere with what you can do !!<br /> <br />SCJP & SCWCD 1.4
A shorter and more readable, but not necessarily more efficient, chunk of code might split the string into words, then concatenate the words back toegether with one space between them. Look at the APIs for String.split() or StringTokenizer or Scanner and see what you think.
My old favorite language, REXX, has a built-in function that puts a specified number of blanks between words. For some reason I used to use zero blanks fairly often.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi