Java Insert randomly into String - java

How do i insert a random variable into a string?
I created a a variable that gets me a random position in the string that i want to put a char in, but I do not know how to use that random value in order to put that char in that certain position. Here is the code I did to get the random variable-
r=0+Math.random()*intTop;
I know this gives me a double, which is why i will cast it later. intTop is the length of the string that i will put the char in. I did this substring and it does not work,-
stringTop=stringTop.substring((int)r,lastBot);
lastBot is the char variable that i want to insert at position r of the string. Please help I am truly stuck.

Java Strings are immutable which means you cannot modify a String in place. Rather, you should create a new string. You can accomplish this by splitting the original string into two parts and inserting the new character in between. Something like this,
stringTop.substring(0, r) + lastBot + stringTop.substring(r);
Hope this helps you

to put a char in a certain position of a string
char[] chars = str.toCharArray();
chars[r] = c;
str = new String(chars);
or
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(r, c);
str = sb.toString();

Related

How to replace first and middle char in string

I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.

Converting an integer and a character to a string in java

I'm trying to create a string comprised of a single letter, followed by 4 digits e.g. b6789. I'm getting stuck when I try to convert a character, and integer to one String. I can't use toString() because I've overwritten it, and I assume that concatenation is not the best way to approach it? This was my solution, until I realised that valueof() only takes a single parameter. Any suggestions? FYI - I'm using Random, because I will be creating multiples at some point. The rest of my code seemed irrelevant, and hence has been omitted.
Random r = new Random();
Integer numbers = r.nextInt(9000) + 1000;
Character letter = (char)(r.nextInt(26) + 'a');
String strRep = String.valueOf(letter, numbers);
I think they mean for you not to use concatenation with + operator.
Rather than that, there's a class called StringBuilder which will do the trick for you. Just create an empty one, append anything you need on it (takes Objects or primitives as arguments and does all the work for you), and at the end, just call at its "toString()" method, and you'll have your concatenated String.
For example
StringBuilder sb = new StringBuilder();
sb.append("Foo");
sb.append(123);
return sb.toString();
would return the string Foo123
you can use:
Character.toString(char)
which is
String.valueOf(char)
in reality which also works.
or just use
String str = "" + 'a';
as already mentioned but not very efficient as it is
String str = new StringBuilder().append("").append('a').toString();
in reality.
same goes for integer + string or char + int to string. I think your simpliest way would be to use string concatenation
Looks like you want
String.valueOf(letter).concat(numbers.toString());

How to populate an array from each character in an element from another array?

Essentially I have an array named symbols String[] symbols = {"a*", "j^", "y!"}
which from that I would like to create another array with each of the single characters from the symbols array being in a single element in the new array, something like this char[] newArr = {'a', '*' ..... }.
In terms me solving this my guess would be to iterate over the elements in the first array then in a nested loop loop over the single characters in that element then assign it to the new array there, but I am unsure how to do that.
I suggest you start by making a single String from your String[] symbols. You might use a for-each loop and a StringBuilder and something like
String[] symbols = { "a*", "j^", "y!" };
StringBuilder sb = new StringBuilder();
for (String symbol : symbols) {
sb.append(symbol);
}
Then you can use String.toCharArray() to convert that into a char[]
char[] chars = sb.toString().toCharArray();
System.out.println(Arrays.toString(chars));
Output is
[a, *, j, ^, y, !]
I won't give you a full solution, but I'll guide you so you have something to begin with.
Iterate on symbols array, it contains String. You can construct a new char array using String#toCharArray, then you'll have each char from each String that you can easily create a String from it and insert it to the new array.
This might solve your problem:
int length = 0;
for(final String s : symbol) { //first get the length of the new array
length += s.length;
}
char[] result = new char[length];
int pos = 0;
for(final String s : symbol) { //then fill the new array with data
System.arraycopy(s.toCharArray(), 0, result, pos, s.length());
pos += s.length();
}
So first of all, it counts how long the result will be by just summing up the lengths of all inputs. This is necessary in order to initialize the char[] with a given length.
Now we already have our empty result array with the right size and can simply fill it with our input.
We do this by iterating through every input string and copying its .getCharArray() into the result array at the current position. After each input symbol copied into our result, we increase pos so that the next entry will be copied into the right position.
JavaDoc of System.arraycopy(src, srcPos, dest, destPos, length)
This also uses no unnecessary Collection API classes and works fine with Java primitives :)

Java - accessing characters in a string in a 2D-array-like manner?

Is there a more or less easy way (without having to implement it all by myself) to access characters in a string using a 2D array-like syntax?
For example:
"This is a string\nconsisting of\nthree lines"
Where you could access (read/write) the 'f' with something like myString[1][12] - second line, 13th row.
You can use the split() function. Assume your String is assigned to variable s, then
String[] temp = s.split("\n");
That returns an array where each array element is a string on its own new line. Then you can do
temp[1].charAt(3);
To access the 3rd letter (zero-based) of the first line (zero-based).
You could do it like this:
String myString = "This is a string\nconsisting of\nthree lines";
String myStringArr[] = myString.split("\n");
char myChar = myStringArr[1].charAt(12);
To modify character at positions in a string you can use StringBuffer
StringBuffer buf = new StringBuffer("hello");
buf.insert(3, 'F');
System.out.println("" + buf.toString());
buf.deleteCharAt(3);
System.out.println("" + buf.toString());
Other than that splitting into a 2D matrix should be self implemented.
Briefly, no. Your only option is to create an object that wraps and interpolates over that string, and then provide a suitable accessor method e.g.
new Paragraph(myString).get(1,12);
Note that you can't use the indexed operator [number] for anything other than arrays.

String Manipulation in java

I have one array of strings. I want to get each of string, divide it in to 3 parts (number-string-number), and put each part in another array. At last I want to have 3 arrays which two of them store numbers and one of them stores strings. The number of spaces between numbers and strings are not fixed.
the format of the strings in the first array is:
-2.2052 dalam -2.7300
-3.0511 dan akan -0.1116
It will be great if you help me with a sample code.
Here's the algorithm you could implement :
Create your 3 output arrays. They should all have the same length as the original string array
iterate through your original array.
for each string, find the index of the first space character and the index of the last space character. (look into the javadoc of the String class for methods doing that)
extract the substring before the first space, the substring between the first and last space, and the substring after the last space. The javadoc should help you.
Convert the first and third substring into an int (see the javadoc for Double for how to do it)
store the doubles and the string into the ouput arrays.
You can use indexOf and lastIndexOf to achieve this. Try following:
String arrayWithStringAndNumber[] = new String[2];
arrayWithStringAndNumber[0] = "-2.2052 dalam -2.7300";
arrayWithStringAndNumber[1] = "-3.0511 dan akan -0.1116";
String numArray1[] = new String[2];
String numArray2[] = new String[2];
String strArray[] = new String[2];
String temp;
for (int i = 0; i < arrayWithStringAndNumber.length; i++) {
temp = arrayWithStringAndNumber[i];
numArray1[i]=temp.substring(0,temp.indexOf(" "));
numArray2[i]=temp.substring(temp.lastIndexOf(" ")+1);
strArray[i]=temp.substring(temp.indexOf(" ")+1,temp.lastIndexOf(" "));
}
Make sure all arrays are of same length.
For num arrays use type whatever you want. I think you may need double and then you can easily parse the value to fit in it.
Hope this helps.
You can use indexOf(int ch) and lastIndexOf(int ch) of String object to find the first and last whitespace character and divide the string using these two indexes. You can also trim the middle string part if needed.
So:
String[] input; // given
Double[] firstNumbers = new Double[input.length];
String[] middleParts = new String[input.length];
Double[] secondNumbers = new Double[input.length];
for(int i = 0; i < input.length; i++) {
String line = input[i];
int firstWhitespace = line.indexOf(" ");
int lastWhitespace = line.lastIndexOf(" ");
String firstNumber = line.substring(0, firstWhitespace);
String middlePart = line.substring(firstWhitespace, lastWhitespace+1);
String secondNumber = line.substring(lastWhitespace+1, line.length());
// parse numbers to double, add to an array
firstNumbers[i] = Double.parseDouble(firstNumber);
middleParts[i] = middlePart;
secondNumbers[i] = Double.parseDouble(secondNumber);
}
Usually every programming language has functions for operating on strings data. Common set of functions is
length (or len) - to get length of string
find (or indexOf or somthing like this) - to find position of character of substring
substring (or substr) - to get substring of N characters from postion P
often
left/right - to get substring of N characters from left or right string's side
Trim/leftTrim/rightTrim - to trim from left and/or right string's side all space-characters or given as function parameter character.
Always as you need to operate on strings data, try to read documentation or google. You always will find information at Internet. Good luck!

Categories

Resources