Search code examples
javastringrandomstringbuilder

Generate a String for a given size


How can I generate a String of a given size?

int someLimit = GlobalLimits.BULK_SIZE;

I want 3 Strings which satisfy the below conditions.

- RandomStr.length < someLimit.length

- RandomStr.length = someLimit.length

- RandomStr.length > someLimit.length

This is what I have tried so far.

private String getLowerRandomString(int upto){
  StringBuilder sBuilder = new StringBuilder();
  for (int i = 0; i < upto; i++){
    sBuilder.append("A");
  }

  return sBuilder.toString();
}

The problem what I see is, if my limit = 10000, it still loop up-to 9999 which is unnecessary. Share if you know a better approach than this. Thank you.


FYI: I was writing a unit test for a simple helper method.

public boolean isBulk(String text){
 int bulkLimit = ImportToolkit.getSizeLimit();
 if (text != null && text.length() > bulkLimit){
  return true;
 }
 return false;
}

So, I want to pass different sizes of strings as parameters to this method and want to assert whether it gives me expected results.


Solution

  • What about using apache commons? It has a RandomStringUtils class that provides exactly the functionality you're looking for, but in the end it loops too...

    org.apache.commons.lang3.RandomStringUtils#randomAlphanumeric(int count)
    

    From JavaDoc

    Creates a random string whose length is the number of characters specified.
    
    Characters will be chosen from the set of alpha-numeric characters.
    
    Parameters:
        count - the length of random string to create
    Returns:
        the random string
    

    If it doesn't need to be random there is another, cheaper method in Stringutils:

    org.apache.commons.lang3.StringUtils#repeat(char, int)
    

    But in the end it too loops...

    From JavaDoc

    Returns padding using the specified delimiter repeated to a given length.
    
     StringUtils.repeat('e', 0)  = ""
     StringUtils.repeat('e', 3)  = "eee"
     StringUtils.repeat('e', -2) = ""
    
    
    Note: this method doesn't not support padding with Unicode Supplementary Characters as they require a pair of chars to be represented. If you are needing to support full I18N of your applications consider using repeat(String, int) instead.
    
    Parameters:
        ch - character to repeat
        repeat - number of times to repeat char, negative treated as zero
    Returns:
        String with repeated character
    See Also:
        repeat(String, int)