开发者

java: How to check StringBuilder charcters to see if it contains same characters as new string request from array?

开发者 https://www.devze.com 2023-01-05 23:16 出处:网络
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 nu

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 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.


You shouldn't be "checking" anything to do that, you should do it so that duplicates never get added in the first place. To do that:

  1. start with a List<String> of the options
    • copy the list
    • add a random element to the result
    • remove that element.
    • Go back to 3 until you've added as many elements as you want or there aren't anymore left


import java.util.Random;

public class Test {
    public static void main(String args[]) {
        String[] fruits = { "apple", "pear", "orange", "peach", "cherry" };

        StringBuilder sb = new StringBuilder("Some fruits: apple");

        Random r = new Random();
        int N = 3;
        for (int i = 0; i < N; i++) {
            String toAdd;
            do {
                toAdd = fruits[r.nextInt(fruits.length)];
            } while (sb.indexOf(toAdd) != -1);

            sb.append(", " + toAdd);
        }

        System.out.println(sb);
    }    
}

Output:

Some fruits: apple, pear, orange, peach

But I agree with Michael Borgwardt on that it's a bad thing to check using index-of over and over again.


A simple way to do it is similar to Marc van Kempen's solution but smaller.

Set<String> fruits = new HashSet<String>();
StringBuilder sb = new StringBuilder();
for (String fruit: fruits) {
    if(fruits.add(fruit)){
        sb.append(fruit);
        sb.append(", ");
    }
}
return sb.toString();


strb2.indexOf(String.valueOf(strb1.charAt(i))

strb2 and strb1 are objects of StringBuilder class. If the letter is present, it will return its index else -1.


Java StringBuilder doesn't have contains method So you can check whether a string or character contains in the StringBuilder as below:

StingBuilder sb = new StringBuilder("apple, pear, orange, peach, cherry");
if(sb.indexOf("someFruit") == -1) {
   //you can insert
} else {
   // do something
}


//StringBuilder object

    StringBuilder sb = new StringBuilder("One Two Three");
    
    System.out.println( contains(sb, "One") );
    System.out.println( contains(sb, "Two") );
    System.out.println( contains(sb, "Five") );

Output:

true
true
false


StringBuilder doesn't have a contains() method, but it does have the indexOf() method. Therefore, you can check for the index of character and if it returns -1, the character is not present in the StringBuilder.

StringBuilder sb = new StringBuilder();

if(sb.indexOf(CharacterYouWantToCheck) != -1){
   //sb contains character
}


Here I iterate through the String to find a matching char in the StringBuilder using chars().forEach()

public static void findMatch(String s){

    StringBuilder sb = new StringBuilder();
    sb.append("can");
    s.chars().forEach(i -> {

        if(sb.indexOf(String.valueOf((char)i))!= -1)
            System.out.println("Found char is "+String.valueOf((char)i));
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消