'Creating a string of a specific size (in bytes)
I have an application where I want to have a method that creates a string of a specified size in bytes.
here's what I basically wrote. I just want to make sure that this produces for example a string of size bytes
static String createMsg(int size){
byte[] msgB= new byte[size];
for(int i = 0; i < size; i++){
msgB[i] = 105;
}
String x = new String(msgB);
return x;
}
Thank you.
Solution 1:[1]
To create a string of a specific size in byte, you must create a string only containing ASCII characters. All characters between 0x0 (0) and 0x7F (127) are ASCII characters and each ASCII character takes one byte. It takes even one byte, if our encoding is UTF, as the first 128 characters in UTF and ASCII are the same for compatiblity reasons.
You can also rely on Apache Commons 3 and use this code snippet to generate a string of a specific size.
RandomStringUtils.randomAscii(100);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
