Editing Unicode within a String - java

I wanted to have a List with Unicode Strings, but I wondered if I could use a for loop instead of adding 9 variables by hand. I tried the following code, but it didn't work.
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add("\u003" + i + "\u20E3");
}
My IDEA gives me an 'illegal unicode escape' error.
Is there an other way to accomplish this?

The easiest way to convert a number to a character within a string is probably using a Formatter, via String.format:
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add(String.format("%c\u20e3", 0x0030 + i));
}

Assuming you want to display the character \u003i, with ifrom 1 to 9, and \u20E3, remember a character is like a number and can be used in mathematical operation.
get the character \u0030: '\u0030'
add i : '\u0030' + i
concatenate the new character with the other one (as a string)
Then print the result:
System.out.println((char)('\u0030' + i) + "\u20E3");

Related

Java - Finding a certain string in JTextArea

I'm creating a simple program that gets 2 certain strings on an input from a JTextArea. It needs to find a non-integer string then finds an integer. All values matching from the same non-integer string will add and display the result in a JTextField. Like in the example below, all numbers who matches "ax" will be added together and the final result will be displayed in the texfield below the label "AX Box" (25 + 5 = 30)
My following code:
JTextField ax, bx, cx, dx;
int totalAX, totalBX, totalCX, totalDX;
String[] lines = textArea.getText().split("\\n"); // split lines
System.out.println(Arrays.toString(lines)); // convert each line to string
for (int i = 0; i < lines.length; i++) {
if (lines.contains("ax") {
// add each numbers.
// for example, 25 + 5
totalAX = totalAX + i;
ax.setText("Total: " +totalAX);
}
}
My problem is that the program cannot find the substring "ax", "bx" and so on. What's the best approach in this? I get errors like:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "ax"
I'm not sure that you're actually splitting the array, the escape sequence for a line jump is \n, you have it as \\n.
You are also only printing the array lines if you need to convert it to String you should be reassigning a value for it like:
for (int i = 0; i < lines.length; i++) {
String line = lines[i].toString();
And I'm pretty sure you don't need the toString() as it should come as a String variable from the textBox
After this you need to find if it contains the "ax" and the index where it is first contained, keep that number and use it to substring the whole line to find the number, so bearing in mind that the number should be in the last place of the string you would be looking at something like this after (inside) the loop:
if (line.contains("ax") {
int theIndex = line.indexOf("ax");
line = line.substring(theIndex);
}
Or in a oneliner:
if (line.contains("ax") {
line = line.substring(line.indexOf("ax"));
}
I used regex to extract numbers from the lines that match your text.
Pattern pattern = Pattern.compile("[0-9]+");
Matcher m;
System.out.println(Arrays.toString(lines));
for (int i = 0; i < lines.length; i++) {
if (lines[i].contains("ax")) {
m = pattern.matcher(lines[i]);
if (m.find()) {
totalAX += Integer.parseInt(m.group());
}
}
}
ax.setText("Total: " +totalAX); //put this line outside of the loop so that it will show the totalAX after all numbers have been read.

How to explode a string on a hyphen in Java?

I have a task which involves me creating a program that reads text from a text file, and from that produces a word count, and lists the occurrence of each word used in the file. I managed to remove punctuation from the word count but I'm really stumped on this:
I want java to see this string "hello-funny-world" as 3 separate strings and store them in my array list, this is what I have so far , with this section of code I having issues , I just get "hello funny world" seen as one string:
while (reader.hasNext()){
String nextword2 = reader.next();
String nextWord3 = nextword2.replaceAll("[^a-zA-Z0-9'-]", "");
String nextWord = nextWord3.replace("-", " ");
int apcount = 0;
for (int i = 0; i < nextWord.length(); i++){
if (nextWord.charAt(i)== 39){
apcount++;
}
}
int i = nextWord.length() - apcount;
if (wordlist.contains(nextWord)){
int index = wordlist.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else{
wordlist.add(nextWord);
count.add(1);
if (i / 2 * 2 == i){
wordlisteven.add(nextWord);
}
else{
wordlistodd.add(nextWord);
}
}
This can work for you ....
List<String> items = Arrays.asList("hello-funny-world".split("-"));
By considering that you are using the separator as '-'
I would suggest you to use simple split() of java
String name="this-is-string";
String arr[]=name.split("-");
System.out.println("Here " +arr.length);
Also you will be able to iterate through this array using for() loop
Hope this helps.

Java automatic filling of ArrayList, searching for better options

I'm using this code here to automatically fill a string array list with the directory path of obj files for later use in animations, but there's a small problem with this:
private List<String> bunny_WalkCycle = new ArrayList<String>();
private int bunny_getWalkFrame = 0;
private void prepare_Bunny_WalkCycle() {
String bunny_walkFrame = "/bunnyAnimation/bunnyFrame0.obj";
while(bunny_WalkCycle.size() != 30) { // 30 obj files to loop through
if(bunny_getWalkFrame != 0) {
bunny_walkFrame =
"/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_"+bunny_getWalkFrame+".obj";
}
bunny_WalkCycle.add(bunny_getWalkFrame);
bunny_getWalkFrame++;
}
}
Now the problem is that the naming convention in blender for animations has zeros before the actual numbers, so something like this:
bunnyWalkFrame_000001.obj
bunnyWalkFrame_000002.obj
bunnyWalkFrame_000003.obj
...
bunnyWalkFrame_000030.obj
With my prepare_Bunny_WalkCycle method I cannot account for the zeros so I would change the names and get rid of the zeros.. This may be okay for not so many frames but once I hit 100 frames it would get painfull.. So there's my question:
What would be an intelligent way to account for the zeros in the code instead of having to rename every file manually and remove them?
I think you can solve your problem with "String.format":
String blenderNumber = String.format("%06d", bunny_getWalkFrame);
Explanation:
0 -> to put leading zeros
6 -> "width" of them / amount of them
And so this would be your new bunny_walkFrame:
bunny_walkFrame = "/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_" + blenderNumber + ".obj";
You can use String.format() to pad your numbers with zeros:
String.format("%05d", yournumber);
Here are two options. First, you can use a string formatter to create your filenames with leading zeros:
bunny_WalkCycle.add("/bunnyAnimation/bunnyFrame0.obj");
for (int frame = 1; frame <= 30; frame++) {
bunny_WalkCycle.add(
String.format("/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_%06s.obj", frame));
}
The second option is, if you already have all the required files in the directory, you can get them all in one go:
bunny_WalkCycle.add("/bunnyAnimation/bunnyFrame0.obj");
bunny_WalkCycle.addAll(Arrays.asList(new File("/bunnyAnimation/bunnyWalkAnim").list()));
There are two ways you could do that:
Appending the right number of leading zeroes, or using a String formatter.
bunny_walkFrame = "/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_" + String.format("%05d", bunny_getWalkFrame) + ".obj";
OR
bunny_walkFrame = "/bunnyAnimation/bunnyWalkAnim/bunnyWalkFrame_" + getLeadingZeroes(bunny_getWalkFrame) + String.valueOf(bunny_getWalkFrame) + ".obj";
where
private String getLeadingZeroes(int walk) {
String zeroes = "";
int countDigits = 0;
while (walk > 0) {
countDigits++;
walk /= 10;
}
for (int i = 1; i <= (nZeroes - countDigits); i++) {
zeroes += "0";
}
return zeroes;
}
Here ya go:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
Just specify how many digits you want. Set it to one. If it has to it will push over (so it won't cut digits off)

Convert middle substring to "*"

I have a string String email="rachitgulati26#gmail.com" so its length is 24.
I want result like rachit************il.com.That means 1/4 of initial same and last 1/4 same.
Just want to convert 1/2 from middle to * with the help of regEX.
Thanks
You could do something like this:
"rachitgulati26#gmail.com".replaceAll("(?<=.{5}).(?=.{5})", "*");
this will replace all characters to * apart from the first and last 5.
In response to your question, you could make this flexible like this:
String email = "rachitgulati26#gmail.com";
int i = email.length() / 4;
email = email.replaceAll("(?<=.{" + i + "}).(?=.{" + i + "})", "*");
Just a word of warning, if you were to start using this in production code, you probably want to create a way of caching these regexes, based on the value of i. This way is for demonstration of the pattern only, and will compile a regex Pattern each time it is used.
One way to do it is to create a string of '*'s that is the correct length, then concatenate on the surrounding parts of the original string. That way you don't have to do any looping:
public static String starize(String str){
char[] middle = new char[str.length()/2];
Arrays.fill(middle, '*');
return str.substring(0, str.length()/4)
+ String.copyValueOf(middle)
+ str.substring(3 * str.length() / 4);
}
You could convert to char array, process and convert back to String:
String email = "rachitgulati26#gmail.com";
char[] a = email.toCharArray();
for (int i = 0, j = a.length >> 2; i < a.length >> 1; i++, j++)
a[j] = '*';
email = new String(a);
Result:
rachit************il.com
You can't identify the middle of a string using a single regular expression unless the lengths have a finite number of values.

Java characters count in an array

Another problem I try to solve (NOTE this is not a homework but what popped into my head), I'm trying to improve my problem-solving skills in Java. I want to display this:
Students ID #
Carol McKane 920 11
James Eriol 154 10
Elainee Black 462 12
What I want to do is on the 3rd column, display the number of characters without counting the spaces. Give me some tips to do this. Or point me to Java's robust APIs, cause I'm not yet that familiar with Java's string APIs. Thanks.
It sounds like you just want something like:
public static int countNonSpaces(String text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != ' ') {
count++;
}
}
return count;
}
You may want to modify this to use Character.isWhitespace instead of only checking for ' '. Also note that this will count pairs outside the Basic Multilingual Plane as two characters. Whether that will be a problem for you or not depends on your use case...
Think of solving a problem and presenting the answer as two very different steps. I won't help you with the presentation in a table, but to count the number of characters in a String (without spaces) you can use this:
String name = "Carol McKane";
int numberOfCharacters = name.replaceAll("\\s", "").length();
The regular expression \\s matches all whitespace characters in the name string, and replaces them with "", or nothing.
Probably the shortest and easiest way:
String[][] students = { { "Carol McKane", "James Eriol", "Elainee Black" }, { "920", "154", "462" } };
for (int i = 0 ; i < students[0].length; i++) {
System.out.println(students[0][i] + "\t" + students[1][i] + "\t" + students[0][i].replace( " ", "" ).length() );
}
replace(), replaces each substring (" ") of your string and removes it from the result returned, from this temporal string, without spaces, you can get the length by calling length() on it...
The String name will remain unchanged.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
cheers
To learn more about it you should watch the API documentation for String and Character
Here some examples how to do:
// variation 1
int count1 = 0;
for (char character : text.toCharArray()) {
if (Character.isLetter(character)) {
count1++;
}
}
This uses a special short from of "for" instruction. Here's the long form for better understanding:
// variation 2
int count2 = 0;
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
if (Character.isLetter(character)) {
count2++;
}
}
BTW, removing whitespaces via replace method is not a good coding style to me and not quite helpful for understanding how string class works.

Categories