This question already has answers here:
How to generate a random alpha-numeric string
(46 answers)
Closed 9 years ago.
I am using String Builder from another answer, but I can't use anything but alpha/numeric, no whitespace, punctuation, etc. Can you explain how to limit the character set in this code? Also, how do I insure it is ALWAYS 30 characters long?
Random generator = new Random();
StringBuilder stringBuilder = new StringBuilder();
int Length = 30;
char tempChar ;
for (int i = 0; i < Length; i++){
tempChar = (char) (generator.nextInt(96) + 32);
stringBuilder.append(tempChar);
I have looked at most of the other answers, and can't figure out a solution to this.
Thanks. Don't yell at me if this is a duplicate. Most of the answers don't explain which part of the code controls how long the generated number is or where to adjust the character set.
I also tried stringBuilder.Replace(' ', '1'), which might have worked, but eclipse says there is no method for Replace for StringBuilder.
If you want to control the characterset and length take for example
public static String randomString(char[] characterSet, int length) {
Random random = new SecureRandom();
char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
// picks a random index out of character set > random character
int randomCharIndex = random.nextInt(characterSet.length);
result[i] = characterSet[randomCharIndex];
}
return new String(result);
}
and combine with
char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
to specify the characterset.
It's not based on StringBuilder since you know the length and don't need all the overhead.
It allocates a char[] array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.
more example use here: http://ideone.com/xvIZcd
Here's what I use:
public static String randomStringOfLength(int length) {
StringBuffer buffer = new StringBuffer();
while (buffer.length() < length) {
buffer.append(uuidString());
}
//this part controls the length of the returned string
return buffer.substring(0, length);
}
private static String uuidString() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
You may try this:
//piece
int i = 0;
while(i < length){
char temp =(char) (generator.nextInt(92)+32);
if(Character.isLetterOrDigit(temp))
{
stringBuilder.append(temp);
++i;
}
}
System.out.println(stringBuilder);
Should achieve your goal
Related
I have a string "1234567(Asics (アシックスワーキング) )". It has unicode character, some are a part of ASCII and some are not. What java does is that it takes one byte for ASCII character and two bytes for other unicode characters.
Some part of my program is unable to process the string in this format. So I wanted to encode the values into escaped sequences.
So the string
"1234567(Asics (アシックスワーキング) )"
would map to
"\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0028\u0041\u0073\u0069\u0063\u0073\u0020\u0028\u30a2\u30b7\u30c3\u30af\u30b9\u30ef\u30fc\u30ad\u30f3\u30b0\u0029\u0020\u0029"
.
I wrote this function to do this :-
public static String convertToEscaped(String utf8) throws java.lang.Exception
{
char[] str = utf8.toCharArray();
StringBuilder unicodeStringBuilder = new StringBuilder();
for(int i = 0; i < str.length; i++){
char charValue = str[i];
int intValue = (int) charValue;
String hexValue = Integer.toHexString(intValue);
unicodeStringBuilder.append("\\u");
for (int length = hexValue.length(); length < 4; length++) {
unicodeStringBuilder.append("0");
}
unicodeStringBuilder.append(hexValue);
}
return unicodeStringBuilder.toString();
}
This was working fine outside of my program but caused issues inside my program. This was happening to the line char[] str = utf8.toCharArray();
Somehow I was loosing my japanese unicode characters and this was happening because t was dividing these characters into 2 in the char array.
So I decided to go with byte [] instead.
public static String convertToEscaped(String utf8) throws java.lang.Exception
{
byte str[] = utf8.getBytes();
StringBuilder unicodeStringBuilder = new StringBuilder();
for(int i = 0; i < str.length - 1 ; i+=2){
int intValue = (int) str[i]* 256 + (int)str[i+1];
String hexValue = Integer.toHexString(intValue);
unicodeStringBuilder.append("\\u");
for (int length = hexValue.length(); length < 4; length++) {
unicodeStringBuilder.append("0");
}
unicodeStringBuilder.append(hexValue);
}
return unicodeStringBuilder.toString();
}
Output :
\u3132\u3334\u3536\u3738\u2841\u7369\u6373\u2028\uffffe282\uffffa1e3\uffff81b7\uffffe283\uffff82e3\uffff81af\uffffe282\uffffb8e3\uffff82af\uffffe283\uffffbbe3\uffff81ad\uffffe283\uffffb2e3\uffff81b0\u2920
But this is also wrong as I am merging two single byte characters into one. What can I do to overcome this?
I don't know your other code's specific requirements. But my advice is to not reinvent the wheel and use the built-in encoding capabilities of the API.
For instance call getBytes with either StandardCharsets.UTF_16BE or StandardCharsets.UTF_16LE based on the endian-ness you need:
String s = "1234567(Asics (アシックスワーキング) )";
byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
byte[] utf16 = s.getBytes(StandardCharsets.UTF_16BE); // high order byte first
System.out.println(s.length()); // 28
System.out.println(utf8.length); // 48
System.out.println(utf16.length); // 56 (2 bytes for each char)
As they commented above the internal representation of string in java is utf-16. Found
Character.codePointAt() and Integer.toHexString() that are helpful in your case.
Renamed the parameter to just theString, also removed the throws Exception clause from your original method since no exception was thrown. (it is bad practice in general to throw these generic exceptions)
public static String convertToEscaped(String theString) {
char[] charArr = theString.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < charArr.length; i++) {
String hexString = Integer.toHexString(Character.codePointAt(charArr, i));
sb.append("\\u");
if (hexString.length() == 2) {
sb.append("00");
}
sb.append(hexString);
}
return sb.toString();
}
I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA", how can we concatenate it with n times the char '_',knowing that the '_' has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA", the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1:
As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
public class Concatenation {
public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Go to char array, alloting the right size, fill the array, and sum it up back into a string.
Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW:
Actual answer to the question is in the code of that repeat method.
when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.
This question already has answers here:
How to generate a random alpha-numeric string
(46 answers)
Closed 6 years ago.
I'm trying to generate a string between capital A-Z in java using Secure Random. Currently I'm able to generate an alphanumeric string with special characters but I want a string with only upper case alphabets.
public String createRandomCode(int codeLength, String id){
char[] chars = id.toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new SecureRandom();
for (int i = 0; i < codeLength; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
return output ;
}
The input parameters are length of the output string & id whhich is alphanumeric string.Can't understand what modifications to make to the above code to generate only upper case alphabet string. Please help..
Your method randomly selects characters out of the id argument. If you want those to only be uppercase letters, then pass a string with those characters:
String randomCode = createRandomCode(length, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
EDIT If you want to avoid duplicates, you can't just select characters at random. You'll want to shuffle them and pick out the first n characters:
public String createRandomCode(int codeLength, String id) {
List<Character> temp = id.chars()
.mapToObj(i -> (char)i)
.collect(Collectors.toList());
Collections.shuffle(temp, new SecureRandom());
return temp.stream()
.map(Object::toString)
.limit(codeLength)
.collect(Collectors.joining());
}
EDIT 2 Just for fun, here's another way to implement the original random code generator (allowing duplicates):
public static String createRandomCode(int codeLength, String id) {
return new SecureRandom()
.ints(codeLength, 0, id.length())
.mapToObj(id::charAt)
.map(Object::toString)
.collect(Collectors.joining());
}
Here is generator that I wrote and use:
public class RandomGenerator {
private static final String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String generateRandom(int length) {
Random random = new SecureRandom();
if (length <= 0) {
throw new IllegalArgumentException("String length must be a positive integer");
}
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(characters.charAt(random.nextInt(characters.length())));
}
return sb.toString();
}
}
in numChars string you can put any characters you want to be included. int length parameter is the length of generated random string.
Here is an example method that uses the int range for characters A to Z (also this method avoids duplicate characters in the String) :
public String createRandomCode(final int codeLength) {
int min = 65;// A
int max = 90;// Z
StringBuilder sb = new StringBuilder();
Random random = new SecureRandom();
for (int i = 0; i < codeLength; i++) {
Character c;
do {
c = (char) (random.nextInt((max - min) + 1) + min);
} while (sb.indexOf(c.toString()) > -1);
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
return output;
}
The range part comes from this topic : Generating random integers in a specific range
What is the most simple way? Minimizing any imports.
This one is good:
String str = Long.toHexString(Double.doubleToLongBits(Math.random()));
But it's not perfect, for example it complicates with custom length.
Also an option: How to make this String unique?
Create a String of the characters which can be included in the string:
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Generate an integer using the Random class and use it to get a random character from the String.
Random random = new Random();
alphabet.charAt(random.nextInt(alphabet.length()));
Do this n times, where n is your custom length, and append the character to a String.
StringBuilder builder = new StringBuilder(n);
for (int i = 0; i < n; i++) {
builder.append(/* The generated character */);
}
Together, this could look like:
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public String generateString(int length) {
Random random = new Random();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
}
return builder.toString();
}
RandomStringUtils from commons-lang. If you don't wish to import, check out its source.
Acording to a other question made here Split a Hex String without spaces and flip it, I write this new question more clearly here.
I have an Hex String like this:
Hex_string = 2B00FFEC
What I need is to change the order of the Hex String to start from the latest characters, so this would be like this:
Fliped_hex_string = ECFF002B
In the other question I asked a way to achieve this using the .split() method. But there should be another way to get this in a better way.
As simple as you can is
String s = "2B00FFEC";
StringBuilder result = new StringBuilder();
for (int i = 0; i <=s.length()-2; i=i+2) {
result.append(new StringBuilder(s.substring(i,i+2)).reverse());
}
System.out.println(result.reverse().toString()); //op :ECFF002B
OP constrains the character length to exactly 8 characters in comments.
A purely numeric answer (inspired from idioms to convert endianness); saves going to and from strings
n is an int:
int m = ((n>>24)&0xff) | // byte 3 to byte 0
((n<<8)&0xff0000) | // byte 1 to byte 2
((n>>8)&0xff00) | // byte 2 to byte 1
((n<<24)&0xff000000); // byte 0 to byte 3
If you need to convert this to hexadecimal, use
String s = Integer.toHexString(m);
and if you need to set n from hexadecimal, use
int n = (int)Long.parseLong(hex_string, 16);
where hex_string is your initial string. You need to go via the Long parser to allow for negatives.
You could do something like:
String a = "456789AB";
char[] ca = a.toCharArray();
StringBuilder sb = new StringBuilder(a.length());
for (int i = 0; i<a.length();i+=2)
{
sb.insert(0, ca, i, 2);
}
This also extends to longer Strings if needed
Perhaps you should try something as simple as this:
public static String flip(final String hex){
final StringBuilder builder = new StringBuilder(hex.length());
for(int i = hex.length(); i > 1; i-=2)
builder.append(hex.substring(i-2, i));
return builder.toString();
}
public static void main(String args[]){
System.out.println(flip("2B00FFEC"));
}
The output is: ECFF002B
Next time you ask a question, perhaps you should show us some code you've written used in order to solve your problem (and then ask us why your code doesn't work, not your problem). You will not learn anything from us just providing answers without you knowing how they work.
This method seems to do what you want
String changeHexOrder(String s) {
char[] arr = s.toCharArray();
char tmp;
//change positions of [i, i + 1 , , , , , ,length - i - 2, length - i - 1]
for (int i = 0; i < arr.length / 2; i += 2) {
tmp = arr[i];
arr[i] = arr[arr.length-i-2];
arr[arr.length-i-2] = tmp;
tmp = arr[i+1];
arr[i+1] = arr[arr.length-i-1];
arr[arr.length-i-1] = tmp;
}
return new String(arr);
}
This worked for me
StringBuilder lsbToMsb=new StringBuilder();
for(int i=input.length();i>0;i-=2)
{
lsbMsb.append(lsbToMsb.substring(i-2,i));
}
String lsbMsb=lsbMsb.toString();