๐ how can I convert emojis like this to text? I mean to convert a happy face to the words "happy" and so on. Using Java, how can I achieve this?
You may use emoji4j library.
String text = "A ๐ฑ, ๐ถ and a ๐ญ became friendsโค๏ธ. For ๐ถ's birthday party, they all had ๐s, ๐s, ๐ชs and ๐ฐ.";
EmojiUtils.shortCodify(text); //returns A :cat:, :dog: and a :mouse: became friends:heart:. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:.
Since that emoji is simply a standard Unicode code point (U+1F601, see here), probably the best way is to set up a map which translates them into strings.
By way of example, here's a piece of code that creates a string-to-string map to allow you to look up and translate that exact code point:
import java.util.HashMap;
import java.util.Map;
class Xyzzy {
public static Map<String,String> xlat = new HashMap<String, String>();
public static void main (String[] args) {
xlat.put("\uD83D\uDE01", "happy");
System.out.println(xlat.get("\uD83D\uDE01"));
}
}
You can add as many code points to the map as you wish, and use Map.get() to extract the equivalent text for any of them.
Related
How can is use string formatting on the
<string-array><item> - resource in Android?
Should i do it like in the following example(and how should i do it if yes)...
<string-array name="notification-msgs">
<item>%s sent you a message.</item>
<item>%s answered to your Story</item>
</string-array>
or what kind of technique is common to use in this case?
I only know how to Format string resources.(with getString(R.id.mystring,replacevalue))
Thanks for any help!
EDIT:
I tried to use getStringArray(), but this method does not accept more then one argument, which just is an Array-Ressource.
Unfortunately there is no direct way provided by Android to achieve this. Best you can do is:
String.format(getResources().getStringArray(R.array.notification-msgs)[0], "Someone")
Android supports formatting with getString(String str,Object... args). Link here
Or you can wrap formatting with a method.
public static String formatString(String pure,Object... args){
return String.format(pure,args);
}
//Or
public static String formatString(int id,Context context,Object... args){
String pure = context.getString(id);
return String.format(pure,args);
}
I personally prefer second approach, it is easy to mutable in the future.
Say I have an object that I've created to further simplify reading an XML document using the DOM parser. In order to "step into" a node or element, I'd like to use a single line to go from the start of the document to my target data, buried somewhere within the document, while bypassing the extra "fluff" of the DOM parser (such as doc.getElementsByTagName("data").item(0) when there is only one item inside the "data" element).
For the sake of this question, let's just assume there are no duplicate element tags and I know where I need to navigate to to get the data I need from the document, of which the data is a simple string. The idea is to set the simplified reader up so that it can be used for other data in other locations in the document, as well, without having to write new methods all the time. Below is some example code I've tried:
public class SimplifiedReader {
Document doc;
Element ele;
public SimplifiedReader(Document doc) {
this.doc = doc;
ele = doc.getDocumentElement();
}
public SimplifiedReader fromRoot() {
ele = doc.getDocumentElement();
return this;
}
public SimplifiedReader withEle(String elementName) {
ele = ele.getElementsByTagName(elementName).item(0);
return this;
}
public String getTheData(String elementName) {
return ele.getTextContent();
}
}
Example XML File:
<?xml version="1.0" encoding="UTF-8"?>
<fileData>
<subData>
<targetData>Hello World!</targetData>
<otherData>FooBar!</otherData>
</subData>
</fileData>
This results in me being able to navigate the XML file, and retrieve the Strings "Hello World!" and "FooBar!" using this code:
SimplifiedReader sr = new SimplifiedReader(doc);
String hwData = sr.withEle("fileData").withEle("subData").getTheData("targetData");
String fbData = sr.getTheData("otherData");
Or, if I had to go to another thread to get the data "FooBar!", I would just do:
String fbData = sr.fromRoot().withEle("fileData2").withEle("subData2").getTheData("otherData");
Is there a better/more correct way to do this? Edit: Note: This question is more about the method of returning an object from a method inside of it (return this;) in order to reduce the amount of code written to access specific data stored within a tree format and not so much about how to read an XML file. (I originally thought this was the Singleton Pattern until William corrected me... thank you William).
Thanks in advance for any help.
I don't see any trace of the Singleton pattern here. It mostly resembles the Builder pattern, but isn't it, either. It just implements a fluent API.
Your approach seems very nice and practical.
I would perhaps advise not using fromRoot() but instead constructing a new instance each time. The instance is quite lightweight since all the heavyweight stuff resides in the Document instance it wraps.
You could even go immutable all the way, returning a new instance from withEle(). This buys you many cool properties, like the freedom to share the object around, each code path being free to use it as a starting point to fetch something specific relative to it, share it across threads, etc. The underlying Document is mutable, but usually this doesn't create real-life problems when the code is all about reading.
Is there a better/more correct way to do this?
Yes, there are many better ways to extract values from XML.
One would be to use XPath, for example with XMLBeam.
import java.io.IOException;
import org.xmlbeam.XBProjector;
import org.xmlbeam.annotation.XBDocURL;
import org.xmlbeam.annotation.XBRead;
public class App {
public static void main(String[] args) throws IOException {
FileDate fileDate = new XBProjector().io().fromURLAnnotation(FileDate.class);
System.out.println(fileDate.getTargetDate());
// Hello World!
System.out.println(fileDate.getOtherDate());
// FooBar!
}
#XBDocURL("resource://filedate.xml")
public interface FileDate {
#XBRead("/fileData/subData/targetData")
String getTargetDate();
#XBRead("/fileData/subData/otherData")
String getOtherDate();
}
}
I'm trying to create a chess program on the using the GridWorld case study. You may or may not know what that is, but that is irrelevant to my problem. I've only been coding in java for about a year now in my AP computer science class, so I'm relatively new at this. What I am trying to to is convert a string to a color. I have looked it up online and in numerous places I have found this code:
Field field = Color.class.getField("YELLOW");
Color chosen = (Color)field.get(null);
I would also like to use a variable instead of "YELLOW", so this is the code that I would like to use.
Field field = Color.class.getField("chosenColor");
Color chosen = (Color)field.get(null);
But it does not work, and I don't know why. The message that I get is the title of this question. I have no idea what it means, and quite honestly I'm not all familiar with the field class, so that could be the root of my issue, but I'm just not sure. I will post my code, and I hoping that you can either help me with this error, or give me another way to convert strings to colors.
Like I said, I'm relatively new, so it would be great if you could use smaller words that my limited coding knowledge can understand.
package framework.info.gridworld;
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import java.awt.Color;
import java.util.*;
import java.lang.reflect.Field;
/**
* Play a game of chess! Simple, yet oh so complicated.
*
* #author M.A.Williams
* Version one. Started: 5-15-2014 Finished: N/A
*/
public class ChessRunner
{
public static void main(String[]args)
{
Scanner in= new Scanner(System.in);
System.out.println("Pick from one of these colors! \nBlue \nCyan\nGreen\nMagenta\nOrange\nPink\nRed\nWhite\nYellow");
System.out.println("Do not choose Black!!!");
String chosenColor=in.next();
chosenColor=chosenColor.toUpperCase();
while(chosenColor.equals("BLACK"))
{
System.out.println("I told you not to choose Black! Choose a different color!");
chosenColor=in.next();
chosenColor=chosenColor.toUpperCase();
}
Field field = Color.class.getField("YELLOW");
Color chosen = (Color)field.get(null);
ActorWorld chessWorld= new ActorWorld();
Bug playerKing=new Bug(chosen);
chessWorld.add(new Location(7, 8), playerKing);
chessWorld.show();
}
}
If you have a look at the Color API http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
you will see that there is a Field called YELLOW http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html#YELLOW
but there is not one called chosenColor.
In your example there is absolutely not need to use reflection, rather try
if (chosenColor.equals("BLUE"))
chosen = Color.BLUE;
else if (chosenColor.equals("YELLOW"))
chosen = Color.YELLOW;
Reflection and exception handling are advanced topics in Java, and it's best to avoid them. Instead, figure out some other way to convert a string to a color, maybe some if/else statements:
if (chosenColor.equals("BLUE"))
chosen = Color.BLUE;
else if (chosenColor.equals("YELLOW"))
chosen = Color.YELLOW;
// repeat for all the colors
If you don't know how to catch exceptions it is far too soon for you to be using Reflection.
You don't need it here in any case. You should just use Color.YELLOW.
This is the code that I would like to use.
Field field = Color.class.getField("chosenColor");
Color chosen = (Color)field.get(null);
This code is complete nonsense.
MIME message senders appear in formats such as:
"John Doe" <johndoe#gmail.com>
<johndoe#gmail.com>
I'm trying to figure out how to extract the string "johndoe#gmail.com" in the above examples, although I will also need the "johndoe" and "gmail.com" parts (per RFC I'm pretty sure splitting on # is all that's needed from here). Obviously regex-ing up my own parser is one (not great) option.
It seemed this may be possible using javax.mail.internet.MimeMessage. All of the constructors require a Folder which I do not have (well, I sort of do, it exists in the IMAP layer), e.g.
MimeMessage(Folder folder, InputStream is, int msgnum)
Which makes me feel I'm using this class wrong. Nonetheless, if I parse this way I do get access to the getFrom() method which returns an array of Address, which itself doesn't offer methods of use to me.
Using mime4j it's easy to get this far:
case T_FIELD: // field means header
if(token.getName() == "from") {
// get raw string as above - unparsed
So using mime4j or using java, javax etc. utilities it should be possible to extract the "a#b.com" part of the address from there, but I haven't found a class within javax or mime4j that is responsible for this yet.
I think you need InternetAddress class from javax.mail:
http://docs.oracle.com/javaee/6/api/javax/mail/internet/InternetAddress.html#getAddress()
Minimum working example:
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
public class JavaMailExample {
public static void main(String[] args) throws AddressException {
String fullemail = "\"John Doe\" <johndoe#gmail.com>";
InternetAddress addr = new InternetAddress(fullemail);
System.out.println(addr.getPersonal()); // John Doe
System.out.println(addr.getAddress()); // johndoe#gmail.com
}
}
If I have got a whole block of text as a String, which contains several new-lines.
For example: System.out.println(myString) would give:
<http-request>
<param1>value</param>
<param2>value</param>
</http-request>
And what I want to do is space the whole block three tab spaces to the right...
What is the best way to get this done?
Not tried in code but sounds like the replace(regex, string) should work.
Just go for replace("\n", "\n\t\t\t") -> one \t per tab space.
(replace from String's standardlib)
Since java 12 you can use String.indent() method. For example
public static void main(String[] args) {
System.out.println("""
<http-request>
<param1>value</param>
<param2>value</param>
</http-request>
""".indent(8));
}
will produce output like below
<http-request>
<param1>value</param>
<param2>value</param>
</http-request>