Get a random character from the given string – Java Program

Given a string, write a function that returns a random character from the string. 

Example:

Given string = algorithms @ tutorial horizon
Random character: s
Random character: r
Random character: h
Random character: @
Random character: i

Approach:

Get the length of the string and then use the java random function to get the random index between 0 and length and pick the character at that index and if the picked character is empty space then pick some other index.

Complete Code:

Output:

Given string = algorithms @ tutorial horizon
Random character: s
Random character: r
Random character: h
Random character: @
Random character: i

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.