Java : String to table
In Java I have a string like this "0564\n5523\n5445\n8596" and I'd like more or less to make a table like this :
. * . .
* * . .
* . . *
. * . .
In which * means it's equal to 5 and . means it's not equal to 5.
The base string is directly extracted from a text file (still don't know how I will do that, but if someone has simple and clear documentation about it... ;-) ).
The method I want to do is something like this (I know the initial dimensions of the table and the string will always match the dimensions)
int counter = 0;
for (int r=0;r<size;r++)
{
for (int c=0;c<size;c++)
{
if thestring.charAt(counter)=='5'
{
thetable[c][r]='*';
}
else
{
开发者_JAVA百科 thetable[c][r]='.';
}
counter++;
}
counter = counter+2; //To skip the \n.
}
So basically my first question is "Is there an other way to do it?" I quite don't like that one, because "skipping" the characters I don't want to evaluate seems lame.
The second question (I just want to make sure) is "Is \n considered as 2 characters in the string?"
The last question is more about text files, if the text file I extract the string from is on windows won't the string be like "0564\r\n5523\r\n5445\r\n8596" ?
Homework?
public class d {
public static void main(String[] args) {
String s = "0564\n5523\n5445\n8596";
System.out.println(s.replaceAll("[^5\n]", ".")
.replace('5', '*')
.replaceAll("(.)(?!\n|$)", "$1 ")
.replaceAll("(\r|\n|\r\n)", System.getProperty("line.separator")));
}
}
1st question: Why not just do a replaceAll? i.e.
str.replaceAll("5", "*").replaceAll("[0-9]", ".")
2nd question: "\n" is treated as one character.
3rd question: If it was created in Windows.
精彩评论