1

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.

1
  • stringTop.substring(0, r) + lastBot + stringTop.substring(r) ? Commented Mar 8, 2013 at 1:05

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

For the last part, would I add Top.substring(lengthofstring +1) instead of Top.substring(r)? r is the random part of the string that the character gets added to.
@user2146662 - what aseldawy wrote is correct. stringTop.substring(r) returns the substring starting at position r and going to the end of the string. Well, correct assuming you want to insert a character (make the string one character longer). If you wanted to replace the character, you'd say r + 1 instead of r, instead.
I did this - stringTop=stringTop + stringTop.substring(0,(int) r) + lastBot + stringTop.substring((int)r+ 1); and it gives me an error D:
0

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();

2 Comments

Do i need to import anything for this?
nothing, all is in java.lang. r - is your random index, str - string, c - character to set

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.