Home > Net >  splitting a word in a string into each letter
splitting a word in a string into each letter

Time:03-07

So i am basically trying to make wordle in java(if you don't know what it is look it up its a fun word game), and I have a text file of a bunch of words. I randomly pick 1 of the words using a bufferd reader which would be the word you have to guess, I don't know how you would be able to check each letter after you guess a word. I think I need to split the string up into individual letters so I tried doing this line.toCharArray() line being the string name, but that didn't work. here is the code from where i read the line

int min = 1;
    int max = 101;
    Random r = new Random();
    int value = r.nextInt(max-min)   min;
    
    
    int lines = 0;
    File text = new File("text.txt");
     try (BufferedReader br = new BufferedReader(new FileReader(text)))
    {
        String line = null;
        while ((line = br.readLine()) != null) {
            lines  ;
                if(lines == value)
                    line.toCharArray()
                    System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

CodePudding user response:

String.toCharArray() method returns char[] and won't modify the original string

char[] letters = line.toCharArray();
System.out.println(Arrays.toString(letters));

Reference: Java doc

CodePudding user response:

Avoid char

As a 16-bit value, char type is physically incapable of representing most characters. The char type has been essentially broken since Java 2, and legacy since Java 5.

Code points

Instead use code point integer numbers. A code point is the number permanently assigned to each character by the Unicode Consortium.

Here is code to get the code points of some text as an array. This code generates an IntStream to access each character’s code point. Then we collect the elements of that stream into an array of int primitive numbers.

int[] codePoints = line.codePoints().toArray() ;

Now you can loop those code point numbers.

for( int codePoint : codePoints ) 
{
    …
}

You can generate text from the code point numbers in various ways.

Here’s one, using Character.toString.

String s = Character.toString( codePoint ) ;

And another is calling StringBuilder#appendCodePoint.


By the way, the ThreadLocalRandom class has more convenient methods than Random.

This:

int min = 1;
int max = 101;
Random r = new Random();
int value = r.nextInt(max-min)   min;

… becomes this:

int origin = 1, bound = 101;
int value = ThreadLocalRandom.current().nextInt( origin, bound );

Tip: Work on better naming of your variables than “value”.


  • Related