I would like to produce an array of randomly creating strings in a short way. There is such a way in case ints (instead of strings), so I'm searching for something similar using org.apache.commons.lang3.RandomStringUtils instead of java.util.Random.
I've tried to search through methods for RandomStringUtils, but I didn't found anything useful.
The simple code producing an array of 13 pieces of ints is as follows:
java.util.Random r = new java.util.Random();
int[] toReturn = r.ints(0,100).limit(13).toArray();
Is it possible to find something analogous for RandomStringUtils?
RandomStringUtils doesn't have streaming methods, but you could use IntStream to create a stream and then just map it to some random string generation. E.g.:
int len = 10;
int numStrings = 13;
String[] randomStrings =
IntStream.range(0, len).mapToObj(i -> RandomStringUtils.random(len)).toArray(String[]::new);
Related
If i input 1324,3591
It mean i want the bigger denote in order.
int x = 1324;
int y = 3591;
System.out.println(x+y);
I want the output show:
4321 and 8531
Create two function, public int[] orderAsIncreasing(int input[]) and public int[] orderAsDecreasing(int input[]).
Then, loop inside the input searching for the highest value, and place it as the first/last in the output of each function. Remove that value from the array. Repeat until the array is empty. Then return the result
I will not post code, since this looks like some sort of homework. The logic is there. Now, use google and documentations to get the operators for it.
I think you should convert the numbers to strings and then to char arrays. If 'number' is your number, then something like:
String numberAsString = String.valueOf(number);
char[] charArray = numberAsString.toCharArray();
Arrays.sort(charArray);
String newNumberAsString = new String(charArray);
int number2= Integer.valueOf(newNumberAsString);
I am learning Java and looking for a comprehensive code of multiplying the elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of strings and the second is integers?
I'm afraid Java isn't going to support this kind of thing natively, and you'll need to perform some of your own logic to implement it. Let's say you've got your String[]..
String[] a = {"a", "b", "c", "d"};
And you've got your int[]..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a StringBuilder, then you'll import it and declare..
StringBuilder total = new StringBuilder();
NOTE: StringBuilder is strongly recommended here.
And then you're looping multiplier amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of a[x] to the repeated String.
NOTE: Something that's also important is leaning good practise. If you're using Java code, it's considered terrible practise to repeatedly concatenate String objects. StringBuilder is more efficient, and is the Java standard. I would strongly recommend using this.
Have fun putting it all together!!
To create string filled with multiple instances of same character like "ccc" you can firs create array of characters which will hold only 3 characters like
char[] myCharacters = new char[3];
Now this array is filled with zeroes ('\0'), so you need to fill it with desired character 'c'. You simply do it using for loop
for (int i = 0; i<myCharacters; i++){
myCharacters[i] = 'c';
}
After this your array will contain ['c', 'c', 'c'].
Now you can use this array to create string using characters from it. To do so you just need to pass this array to String constructor like
String myString = new String(myCharacters);
And there you go. Now you have "ccc" String. Repeat these steps for each pair of elements from a and b arrays.
You can also use shorter version which kinds of do the same
String myString = new String(new char[3]).replace('\0','c');//will produce "ccc"
I have some problem when using array in Java. If I declare an array of character like this, my program will throw exception "out of bound array":
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
I do not know why it is ok when i replace the first line by:
char[] ipx = new char[64];
I think both of them are correct because i used to delare new string like this:
String newString = "";
what's the difference between those ?
Many thanks for any help you may be able to provide
I do not know why it is ok when i replace the first line by:
Because char[] ipx = {}; is equivalent to char[] ipx = new char[0]; // zero sized array;
and in latter case char[] ipx = new char[64]; you allocate 64 chars for your array.
No, it has to be initialized to a size at some point. In your example, you can just use: myString.toCharArray();
Typically you'd use Lists for things of unknown size and then do myList.toArray();
In a nutshell, you should not attempt to draw any parallels between String and char[]. They are very different creatures in Java.
If you wish to access element k of an array, you need to ensure that k is a valid index (i.e. that the array is large enough). A zero-length array ({}) is not large enough for any element access.
Is it possible to contruct array in Java without number of elements?
In your case, yes, just replace
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
by
char[] ipx = myString.toCharArray();
You can also use a ArrayList<Character> without declaring the number of elements.
Yes, all arrays in java are basic data structures and must have a pre-defined fixed length. Changing the length necessarily requires creating a new array.
If you want to handle collections of objects with variable size, what you want is a Collections Object from the Java libraries, which is more intelligent than a basic data array.
The List class in particular, ArrayList, will perform exactly what you want. It is a List of objects (instead of an array) and will resize itself naturally as you add or remove elements.
If you do char[] ipx = {}, it means you create a reference ipx. Same as you do char* ipx in C++, which is a pointer points to a random address. In order to store elements in it, you need to allocate memory like in C++ you need to do char* ipx = new char[64]. Therefore, if you only do char[]ipx = {} which is equivalent to char[]ipx = new char[0] in Java.
Is it possible to create in Java an array indexed by letter characters ('a' to 'z') rather than by integers?
With such an array "a", I would like to useit in this way, for example
print (a['a']);
Is it possible to create in Java an array indexed by letter characters
('a' to 'z') rather than by integers?
Of course it is possible.
You could do this either like this:
char theChar = 'x';
print (a[theChar - 'a']);
or assuming handling only ASCII strings just declare the array of size 256. The directly index the array using your character.
char[] a = new char[256];
char theChar = 'x';
print (a[theChar]);
Now you don't care if it is uppercase/lower case or whatever.
Actually if you are interested specifically for ASCII strings using a Map could be overkill compared to a simple array. The array doesn't waste so much space and perhaps a Map (a very efficient construct) is too much for such a simple task.
Use a Map instead.
Map<Character, Object> myMap = new HashMap<Character, Object>();
myMap.put('a', something);
print(myMap.get('a'));
On the other hand, as others already suggested, you can use a char as index (but you would leave all array elements 0...'a'-1 empty):
String[] a = new String['z' + 1];
a['a'] = "Hello World";
System.out.println(a['a']);
You could create an array of 26 elements and always substract 'a' from you char index:
int[] array = new int[26];
array['a'-'a']=0;
array['b'-'a']=1;
\\ etc...
What about something simple like this?
public static int getLetterValue(char letter) {
return (int) Character.toUpperCase(letter) - 64;
}
and use it like so:
System.out.println(a[getLetterValue('a'));
This will fail pretty hard as it stand at the moment. You will need to check it's within range etc.
Alternatively you could implement the Java List interface and override the .get and .add methods so that they can use chars. But that brings me to my next point.
It's better to use a data structure that handles exceptions better, and is designed for that sort of use case. A Map is a much better choice.
Yes and no. Yes because you can do it and it will compile. Try the following code:
class foo {
public static void main(String[] args) throws Exception {
int a[] = new int[100];
a['a'] = '1';
System.out.printf("%d\n", a['a']);
}
}
No, because the chars will be implicitly converted to ints, which doesn't sound like what you're looking for.
The data structure you are looking for is called Map in Java land.
This data structure is known by various names, such as associative array in PHP; dictionary in C#, Python; hash in Ruby etc which leads to this kind of confusion.
You could do something like this:- for eg:
char[] a = new char[]{'s','t'};
int[] result = new int[256];
result[a[0]]= 100;
System.out.println(result['s']);//will print 100
No, You cannot do that. In the situation you should use Map instead.
I think this is a duplicate question! See Can Java use String as an index array key? (ex: array["a"]=1;) .
You should use a map to map the letter to the value and call get to get the value.
I would like some guidance on how to split a string into N number of separate strings based on a arithmetical operation; for example string.length()/300.
I am aware of ways to do it with delimiters such as
testString.split(",");
but how does one uses greedy/reluctant/possessive quantifiers with the split method?
Update: As per request a similar example of what am looking to achieve;
String X = "32028783836295C75546F7272656E745C756E742E657865000032002E002E005C0"
Resulting in X/3 (more or less... done by hand)
X[0] = 32028783836295C75546F
X[1] = 6E745C756E742E6578650
x[2] = 65000032002E002E005C0
Dont worry about explaining how to put it into the array, I have no problem with that, only on how to split without using a delimiter, but an arithmetic operation
You could do that by splitting on (?<=\G.{5}) whereby the string aaaaabbbbbccccceeeeefff would be split into the following parts:
aaaaa
bbbbb
ccccc
eeeee
fff
The \G matches the (zero-width) position where the previous match occurred. Initially, \G starts at the beginning of the string. Note that by default the . meta char does not match line breaks, so if you want it to match every character, enable DOT-ALL: (?s)(?<=\G.{5}).
A demo:
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}
which can be tested online here: http://ideone.com/q6dVB
EDIT
Since you asked for documentation on regex, here are the specific tutorials for the topics the suggested regex contains:
\G, see: http://www.regular-expressions.info/continue.html
(?<=...), see: http://www.regular-expressions.info/lookaround.html
{...}, see: http://www.regular-expressions.info/repeat.html
If there's a fixed length that you want each String to be, you can use Guava's Splitter:
int length = string.length() / 300;
Iterable<String> splitStrings = Splitter.fixedLength(length).split(string);
Each String in splitStrings with the possible exception of the last will have a length of length. The last may have a length between 1 and length.
Note that unlike String.split, which first builds an ArrayList<String> and then uses toArray() on that to produce the final String[] result, Guava's Splitter is lazy and doesn't do anything with the input string when split is called. The actual splitting and returning of strings is done as you iterate through the resulting Iterable. This allows you to just iterate over the results without allocating a data structure and storing them all or to copy them into any kind of Collection you want without going through the intermediate ArrayList and String[]. Depending on what you want to do with the results, this can be considerably more efficient. It's also much more clear what you're doing than with a regex.
How about plain old String.substring? It's memory friendly (as it reuses the original char array).
well, I think this is probably as efficient a way to do this as any other.
int N=300;
int sublen = testString.length()/N;
String[] subs = new String[N];
for(int i=0; i<testString.length(); i+=sublen){
subs[i] = testString.substring(i,i+sublen);
}
You can do it faster if you need the items as a char[] array rather as individual Strings - depending on how you need to use the results - e.g. using testString.toCharArray()
Dunno, you'll probably need a method that takes string and int times and returns a list of strings. Pseudo code (haven't checked if it works or not):
public String[] splintInto(String splitString, int parts)
{
int dlength = splitString.length/parts
ArrayList<String> retVal = new ArrayList<String>()
for(i=0; i<splitString.length;i+=dlength)
{
retVal.add(splitString.substring(i,i+dlength)
}
return retVal.toArray()
}