I want to check if a Java StringBuilder
object contains a character.
For example I have a list of foods in an array {apple, pear, orange, peach, cherry} and I want to add a random number of these food types to the StringBuilder.
How would I check if StringBuilder contains a character?
The StringBuilder class does not have a contains() method, but String does. So you can use StringBuilder to build a string by using toString() . Then call contains() on it, to check if it contains that character or string.
The charAt(int index) method of StringBuilder Class is used to return the character at the specified index of String contained by StringBuilder Object.
Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.
2. Equality. We can use the equals() method for comparing two strings in Java since the String class overrides the equals() method of the Object class, while StringBuilder doesn't override the equals() method of the Object class and hence equals() method cannot be used to compare two StringBuilder objects.
The StringBuilder
class does not have a contains()
method, but it does have an indexOf()
method. The indexOf()
method returns -1
when the substring was not found.
Example:
stringBuilder.indexOf(charactersYouWantToCheck)!=-1
The StringBuilder
class does not have a contains()
method, but String
does. So you can use StringBuilder
to build a string by using toString()
. Then call contains()
on it, to check if it contains that character or string.
Example:
stringBuilder.toString().contains(characterYouWantToCheck)
It is of course possible to check the string by iterating through it (e.g. use indexOf()), but I would use a Set in this particular instance to add the fruits (if it already exists it will not be added again), once you're done adding fruits convert the Set into a String, e.g.
Set<String> fruits = new HashSet<String>();
for (String fruit: fruitSource) {
fruits.add(fruit);
}
StringBuilder sb = new StringBuilder();
for (String fruit: fruits) {
sb.append(fruit);
sb.append(", ");
}
return sb.toString();
A different option is to create a List<String>
of all of the options, and use Collections.shuffle
to randomly permute the list. You can then join together the first n elements.
Since both Collections.shuffle
and joining together the first n elements takes linear time, the entire process should take linear time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With