I am a new to Java developing and going to school, I am stuck on this assignment and was hoping if you could point me in the right direction, I have an array and in the array there is an element " saw ", how could I delete the extra space there when I insert into a stringbuilder. I tried the delete() but the problem is if the elements are changed it needs to continue working properly. Here is my code, any feedback would be appreciated.
String[] tools = {"hammer", "NAIL", " saw ", "Screw"};
StringBuilder sb = new StringBuilder("We need ");
for(int i = tools.length - 1; i >= 0; i--){
if(i != 3){
sb.append("s," + tools[i].toLowerCase());
}
else{
sb.append(tools[i].toLowerCase());
}
}
System.out.println(sb.toString() + "s and a lot of time.");
}
}
You should trim() it
if(i != 3){
sb.append("s," + tools[i].toLowerCase().trim());
}
else{
sb.append(tools[i].toLowerCase().trim());
}
String class has trim method.You can use tools[i].trim() to remove spaces and continue appending.It will ignore if no spaces.
If I'm not misunderstood,
if(i != 3)
{
sb.append("s," + tools[i].toLowerCase().trim());
}
else{
sb.append(tools[i].toLowerCase().trim());
}
Related
Code and Error
Error 2
hey Guys see the Image and help me out to sort out this issue
It is the first code and it runs perfectly but when i use the same approach in the blow code it have some error
" For error detail open image link "
String str = "Samaarth";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(3);
System.out.println(sb.toString());
This is where the error start and the error is because of DeleteCharAt() function but in the above code this function works perfectly but here it is not
IDK why so please help me out to sort our this issue
String str= "aaabccddd";
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < str.length() -1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.deleteCharAt(i);
//sb.deleteCharAt(i+1);
}
}
System.out.println(sb.toString());
Samarath, you both modify the string and advance the counter.
This is wrong. Consider the string "aaaa"
This is what your code does:
i = 0: you find the duplicate, remove it. The string becomes "aaa".
Then you advance the position: i becomes 1
i = 1: the string is "a|aa" (the vertical bar shows the position).
You find the duplicate at position 1. You kill it, the string
becomes "aa", but you advance the position one again: i becomes 2
At this step the for loop ends and your string is "aa".
Instead the algorithm should use while loop: "while there are duplicates, kill them!"
String str= "aaabccddd";
StringBuilder sb = new StringBuilder(str);
int i = 0;
while (i < sb.length()-1) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.deleteCharAt(i);
// Do not increment -- kill all duplicates
} else {
// Either not a duplicate, or all duplicated killed
// Advance one char
i++;
}
}
System.out.println(sb.toString());
The output is abcd.
If you are inclined to use for loop, then iterate in the reverse order:
String str= "aaabccddd";
StringBuilder sb = new StringBuilder(str);
for (int i = sb.length()-1; i > 0; i--) {
if (sb.charAt(i) == sb.charAt(i - 1)) {
// Note charAt(i - 1) - we compare with the preceding character
sb.deleteCharAt(i);
// The string squeezes by one char, but the decremented position
// will follow
}
}
System.out.println(sb.toString());
The output is abcd
The problem is you are using for loop and you are actually changing/mutating StringBuilder instance at the same time, so the .length() will not be fixed and eventually you will try to reach non-existing index in your for loop and exception will be thrown.
EDIT:
Add these two lines inside your for loop if statement, just before you invoke deleteCharAt() method:
System.out.println("Value of i is: " + i);
System.out.println("StringBuilder length is: " + sb.length());
"i" represents index you are trying to delete, and sb.length() will display actual length of the StringBuilder.
Basically I've built up a string and I need to put an if statement on when to use a comma and a space. So basically I need it be after the first element and not on the last element.
This is what my current code is:
And the output it returns is
"thing1thing2thing3"
I want to make the output to be
"thing1, thing2, thing3"
And I need an if statement as part of the requirements on when to place the commas and spaces.
Thanks in advance.
This might be a little advanced for you, but it's very easy when using Java 8 (if things is a Collection:
return Optional.of(things.stream()
.filter(thing -> thing.getCategory() == things.STUFF)
.collect(Collectors.joining(", ")))
.orElse("nothing");
If you're using Java 7, then you can do it manually:
StringBuilder sb = new StringBuilder();
for (Thing thing : things) {
if (things.getCategory() == some.STUFF){
sb.append(thing.getName()).append(", ");
}
}
if (s.isEmpty()) {
return "nothing";
}
return sb.delete(sb.length() - 2, sb.length()).toString();
I'd use a for-loop rather than a for-each loop - only because I see it as eliminating the need for an additional counter variable. This is how I'd approach the problem.
String[] things = {"thing 1", "thing 2", "thing 3", "thing 4"};
for(int i = 0; i < things.length; i++)
{
if(i < things.length - 1)
{
System.out.print(things[i] + ", ");
}
else
{
System.out.print(things[i] + ".");
}
}
There are a few unclear things about the question, so the code below is based on what I have understood so far.
String s = "";
boolean isComma = true; // true = comma, false = space.
for (Thing thing : things)
{
if (things.getCategory() == thing.STUFF)
{
//Check if there already exists an entry within the String.
if (s.length() > 0)
{
//Add comma or space as required based on the isComma boolean.
if (isComma)
{
s += ", ";
}
else
{
s += " ";
}
}
s += thing.getName();
}
}
if (s.equals(""))
{
s += "nothing";
}
return s;
I'd like to check if some character is between 2 other chars.
For example, given the following String:
String myString = "Hello, my name is 'Tesda', and this is 'ASDfs'."
I want to check if the 'S' in "ASDfs" is between '' or not, also keeping in mind I want to check every '', not jump directly to the second ''.
I've tried a silly code (I'm not familiar with this at all, as I didn't need it until now), which is:
boolean isBetween;
if (!MyString.substring(MyString.indexOf("'"), MyString.indexOf("'")).contains("S"))
isBetween = true;
Well, this didn't work and I don't understand how to make it perfectly.
Also, I want to replace that S with another letter, but I want only between the '', not the one after "my name is", I thought about getting the index of the letter, if it's inside '', then replace that letter in that specific index, is that possible?
Using the provided answer, I've made the following code ( which why i posted this question for ) :
String NewText = "Hello, My NAme is 'Ba', i'm from 'LA' ";
boolean contains = false;
int indexOfS = -1;
String MyString_temp = NewText;
while (MyString_temp.length() >= 0) {
int first = MyString_temp.indexOf("\'");
if(first == -1)
{
break;
}
int second = MyString_temp.substring((first + 1)).indexOf("\'");
second = second + first + 1;
if(second == -1)
{
break;
}
contains = MyString_temp.substring(first,second).contains("A");
if (contains) {
break;
}
MyString_temp = MyString_temp.substring((second + 1));
}
Log.i("ResultTest","Index is: " + indexOfS + " - Text is: " + MyString_temp);
if(!contains){
Log.i("ResultTest", "Yes " + i);
Log.i("ResultTest","TeF: " +NewText.replace(NewText.substring(indexOfS,indexOfS+1),"Test"));
} else
Log.i("ResultTest", "No " + i);
Output
Index is: -1 - the text here ..
Failed to output, invalid index
Consider using regular expressions. Your example could be as simple as
MyString.matches("\'S\'");
EDIT: Updated answer for updated question: Your initial code block looked like it might have done the trick, however you must remember that indexOf() only returns the first occurence of what you need. This could work:
String MyString_temp = MyString;
String lookingFor = "S";
String separator = "\'";
boolean contains = false;
int indexOfLooking = -1;
while (MyString_temp.length() >= 0) {
int first = MyString_temp.indexOf(separator);
if(first == -1) {
break;
}
int second = MyString_temp.substring(first + 1).indexOf(separator);
second += first + 1;
if(second == -1) {
break;
}
indexOfLooking = MyString_temp.substring(first, second).indexOf(lookingFor);
contains = (indexOfLooking >= 0)
if (contains) {
break;
}
MyString_temp = MyString_temp.substring(second + 1);
}
After the while loop, contains has your answer, and indexOfLooking has the location of S.
With Apache Commons you can use the following method:
StringUtils.substringBetween(str, "'");
to get an String[] with all results use this:
StringUtils.substringsBetween(str, "'", "'");
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());
(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.