I'm currently developing an online Multilingual Dictionary in JSP, for translation I'm using microsoft-translator-java-api, and for finding meaning I'm using services.aonaware.com/DictService/DictService dict service.
first I'm making request to services.aonaware.com/DictService/DictService dict service and I'm getting output after parsing
WORD
know v 1: be cognizant or aware of a fact or a specific piece of information; possess knowledge or information about; "I know that the President lied to the people"; "I want to know who is winning the game!"; "I know it's time" ...
now I want to get
be cognizant or aware of a fact or a specific piece of information; possess knowledge or information about
translated and I want
"I know that the President lied to the people"
be the same so I want to split string when ever ""/ double quote comes any help?
public static void main(String args[])
{
String a = "a; \"b\". c";
System.out.println("Original string:"+a);
// split by "
System.out.println("Split by \"");
for (String string : a.split("\""))
{
System.out.println(string.replaceAll("[.;]", ""));
}
}
Related
Hello im a total beginner in Java and have a problem. In a code below that has an array of fixed list of guests, how can i print emails of these person? The email must consist of 3 first name digits and two first surname digits, and after these are #guest.com. So it looks like this:
adaro#guest.com
thost#guest.com
In this task i must use methods: substring, split, toLowerCase.
Sorry for my english its not perfect. Please help i've tried to solve this but i'm stuck cant manage it.
public class email {
public static void main(String[] args) {
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
}
}
When you are stuck like this, try breaking down the problem bit by bit.
You are saying you don't know how to extract part of string, but also how to print. I'm tempted to give you written instructions and not the full answer to your question because that's how you will learn better.
You need to construct this email for each String in the String[] array. Look for iterating over arrays in java here for example https://www.geeksforgeeks.org/iterating-arrays-java/
For each String which is of this form "Rock Adam" you need to extract the surname and last name. To do this you need to split the String by space " ". How to do that - How to split a String by space
When you split by space you will get another Array of two elements, first will be surname, second will be first name. Use array indecies to access them.
When you access the firstName your next problem is - how do I get the first 3 characters of that String. How to access 3rd or 2nd is the same problem see how to do this here Extract first two characters of a String in Java
Now that you have the substrings you want to know how to concatenate and print them. How to print multiple variables? Answer is here How to print multiple variable lines in Java. Also for transforming the strings to lowercase you can find answer here https://www.w3schools.com/java/ref_string_tolowercase.asp
Try to do some more work yourself following this and you will learn much more than from copy-pasting what someone will give you directly for free.
Lower code solves your problem. String.split(" ") splits the String at the first occurrence of blank space. It gives a String array back which contains both parts of the name. With String.substring() you can get specific parts of the String.
public static void main(String[] args) {
String[] guests = {"Rock Adam",
"Stewart Thomas",
"Anderson Michael"};
for(String guest : guests){
String[] name = guest.split(" ");
String email = name[1].substring(0,3).toLowerCase() + name[0].substring(0,2).toLowerCase() + "#guest.com";
System.out.println(email);
}
}
Below code is exactly what you are looking for (i guess)
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
List<String> emailIdList = new ArrayList<>();
for (String guest : guests) {
String firstName = guest.split(" ")[1];
String lastName = guest.split(" ")[0];
String emailId = firstName.substring(0,2) + lastName.substring(0,1) + "#guest.com";
emailIdList.add(emailId);
}
I used some word counting algorithm and by a closer look I was wondering because I got out less words than originally in the text because they count for example "it's" as one word. So I tried to find a solution but without any success, so I asked myself if their exist anything to transform a "short word" like "it's" to their "base words", say "it is".
Well, basically you need to provide a data structure that maps abbreviated terms to their corresponding long versions. However, this will not be as simple as it sounds, for example you won't want to transform "The client's car." to "The client is car."
To manage these cases, you will probably need a heuristic that has a deeper understanding of the language you are processing and the grammar rules it incorporates.
I just built this from scratch for the challenge. It seems to be working on my end. Let me know how it works for you.
public static void main(String[] args) {
String s = "it's such a lovely day! it's really amazing!";
System.out.println(convertText(s));
//output: it is such a lovely day! it is really amazing!
}
public static String convertText(String text) {
String noContraction = null;
String replaced = null;
String[] words = text.split(' ');
for (String word : words) {
if (word.contains("'s")) {
String replaceAposterphe = word.replace("'", "$");
String[] splitWord = replaceAposterphe.split('$');
noContraction = splitWord[0] + " is";
replaced = text.replace(word, noContraction);
}
}
return replaced;
}
I did this in C# and tried to convert it into Java. If you see any syntax errors, please point them out.
I've tried "\n\n" and "\r" and everything else, including replaceAll("\r\n", "n") and I still do not understand why it doesn't work. I've also tried "\w", "\n", "\n+" - I've basically tried everything under "My split("\n") doesn't work" on Google search.
I'm trying to split a word with a lot of "\n". I basically have two different classes. One generates this word, and via the other class constructor object transfers it into the split("\n") method. But whatever I do, the array still stays empty.
I've also tried word.split(System.getProperty("line.separator")) even though I didn't have a clue as to what it meant, but it also came up under one of the solutions to this problem.
Here's my Code:
//in Class A
public String getWord()
{
word = word +"\n" + horizontal;
return word;
}
//in Class B
classA a = new classA();
String grid = a.getWord();
String [] lines = grid.split("\n");
EDIT: Sorry, typo mistake, I'll just ask again later. I did actually put grid.split("\n") in my code. What now? The array really is empty. I did System.out.println(array.length) and it was 0. Also, I typed System.out.println("array is " + array) and it only gave me "array is" as output. I know I'm making a stupid mistake somewhere, and I know I can't expect people to answer my question if I don't know what info to provide.
I also wanted to add some stuff in the comments section here for the comfort of those sitting in front of their laptops...
word and horizontal is a string. It's actually a crossword puzzle together.
See? Look!
LONDONPYVRAOMNDDEFSG
GCPZVBATHYXAZXEZIMOZ
NKDGBERLINCHPLTMHMSM
ZMUKPGCHRKDTYGIMRLHO
TVRWBXPRETORIAJBVKWT
OGIVSDFULULHQHAHEJNV
PNWEJHBAKBJZNBPARIS
PHKCZCYGTXEEXDUCPMXF
QIMQMABRASILIALJOFJQ
GXNXKTAHIQMMIFPSYDLI
CAIROYKZYSWEFPUZPKRG
BTNAUNIDQAYVYAPGWWIN
QXZMQSZBTCBEIJINGBSD
QWQRYTBPTKRBCJUOMJTV
SODHAMSTERDAMEMSLVAM
YQHEVNXQQJXCDZKEYQVT
NAIROBISVDNTCFJNYDEG
AKXVOIGYTZTJHGIAFIKZ
BAGHDADSADJTWOOMVRYT
YCPOBXQQMQKBTDMYPYWT
It's city names. At the end of this, I'm supposed to show the solution to the puzzle by changing cases. I know how to do this, but the problem is that I can't seperate them into lines anymore. I don't know why. That's my only problem here. It seems to work for everyone, except for me.
Answers with clues will be appreciated? To delve into a dark and deep mystery...
It should be
grid.split("\n");
not
instance.split("\n")
Call grid.split("\n");
You can't split a class.
Better a.getWord().split("\n");
In your code there isn't no method named split , also your didn"t call your method getword inside System.out.println() ....
First Class :
public class A {
public String returnedWord ="";
public String getWord(String word , String horizontal)
{
returnedWord = word +"\n" + horizontal;
return returnedWord ;
}
}
the Second Class :
public class B {
public String word = "Hello";
public String horizontal = "World";
public static void main (String [] args ) {
A a = new A();
System.out.println(a.getword(word,horizontal));
}
}
you will get the output below :
Hello
World
Say I have a string,
String templatePhrase = "I have a string that needs changing";
I also have a method to replace words in any given String. Here is the method:
public String replace(String templatePhrase, String token, String wordToPut) {
return templatePhrase.replace(token, wordToPut);
}
Now say (for the sake of my actual task) I have all the words in my String str in a List named wordsInHashtags. I want to loop through all the words in wordsInHashtags and replace them with words from another List named replacement using the replace() method. Each time the loop iterates, the modified String should be saved so it will hold its replacement(s) for the next loop.
I will post my code if anyone would like to see it, but I think it would confuse more than help, and all I am interested in is a way to save the modified String for use in the next iteration of the loop.
I was just reading about strings in beginning Java 2 the other day, :"Strings Objects are immutable" Cant be changes basically however StringBuffer Objects were created to deal with such a circumstance as i understand it. You could try:
StringBuffer templatePhrase = "I have a string to be changed";
templatePhrase.replace(token, wordToPut);
String replacedString = (String)templatePhrase;
Line 3 may cause a problem?
public class Rephrase {
public static void main(String[] args) {
/***
Here is some code that might help to change word in string. originally this is a Question from Absolute Java 5th edition. It will change two variable whatever you want but algorithm never change.So the input from keyboard or any other input source.
********/
String sentence = "I hate you";
String replaceWord = " hate";
String replacementWord = "love";
int hateIndex = sentence.indexOf(replaceWord);
String fixed = sentence.substring(0,hateIndex)+" "+replacementWord+sentence.substring(hateIndex+replaceWord.length());
System.out.println(fixed);
}
}
I was looking for a little help as I'm at my wits end on how to accomplish this.
The assignment is to read in a file that contains state names, the governor of that state and the compensation he gets.
Example of the file:
California Tim John $50,000 $78,890 $30,000
North Dakota John Jones $30,000 $40,000 $56,000
Washington Susan K. Bones $30,000 $40,000 $56,000
As you can see, a name can contain more than three words (including the middle initial)
The output I'm supposed to get is the presidents name followed by the total compensation..
Example of output:
Susan K. Bones $126,000
I've already written code that prints out the total compensation. But I'm stuck on reading the names. How do I ignore the state names which can contain at most two words and just take the governor's name?
Here is my code for the total compensation.
Also note: I have to use Scanner on this.
Scanner in = new Scanner(file);
in.nextLine();
do {
double totalCompensation = 0.0;
String readLine = in.nextLine();
readLine = readLine.replaceAll(",", "").replace("$", " ");
String presidentName = "";
Scanner readNumber = new Scanner(readLine);
while(readNumber.hasNext()) {
if (readNumber.hasNextDouble())
totalCompensation += readNumber.nextDouble();
else {
readNumber.next();
}
}
Another note: don't worry, I do have a while(in.hasNextLine()) to close the do loop, later on in my code. I just don't really want to paste in the whole thing.
Any hints would be welcome! Thanks!
If you KNOW ahead of time that you will only ever see US state names, you could have your code look for a state name first. Since you know what part is the state name and what part is the compensation, whatever is left must be the governor's name. There's only 50 states, so this isn't impossibly difficult.
If this is more generic and can be a city/country/whatever and not just a US, there's not a way to distinguish without a better separator character (or quotes to define the "state name" and "governor name".
EDIT: You mention that there is a further requirement that the "leader" name will be of the form "Firstname LastName" "Firstname M. Lastname" or "F. Middlename Lastname". NOW you have enough to solve the answer.
As you pull strings out with the scanner, put them in a list (or if you learned this datatype, a stack is more appropriate). Go through the list backwards. If the 2nd element is an initial, you know the name has three parts. If the 3rd element is an initial, you know the name has three parts. If neither is an initial, you know the name has two parts. Whatever is not the name of the leader is the name of the place.
My previous answer utterly failed to use Scanner, which was a stated requirement. As before, I am using the "New," "North," etc, prefix to delineate two word state names.
static String[] TWO_WORD_STATE_PREFIXES = new String[] {"New", "Rhode", "North", "West", "South"};
public static void scanLine(String line) {
Scanner s = new Scanner(line);
String stateName = s.next();
for (String prefix : TWO_WORD_STATE_PREFIXES)
if (stateName.equals(prefix))
stateName += " " + s.next();
String governorName = "";
String nextToken;
while (!(nextToken = s.next()).startsWith("$"))
governorName += nextToken + " ";
governorName = governorName.trim();
int compensation = 0;
while (s.hasNext())
compensation += Integer.parseInt(s.next().replaceAll("[\\$, ]", ""));
System.out.println(stateName + " - " + governorName + " : " + compensation);
}
public static void main(String[] args) {
scanLine("California Tim John $50,000 $78,890 $30,000");
scanLine("Virginia Some Guy $55,000 $71,890 $30,000");
scanLine("South Carolina Bill F. Gates $91,000 $1,200");
scanLine("Vermont Joan Smith $60,000 $78,890 $30,000");
scanLine("North Dakota Tim John $50,000 $78,890 $30,000");
}
Can the file be modified to contain delimiters other than space like semi-colon. Otherwise one option i can think of is store the list of states and iterate through them and check other wise it would be a name. Eg.
List<String> stateNames={"Alabama","Alaska","Texas"};
This question is about efficient string searching. Let's work on determining which part of the string is the city or state name, since once you have that the rest is trivial.
First, you will need a list of cities and states. Here's a list of cities (should be pretty easy to parse out the actual city names) http://www.census.gov/tiger/tms/gazetteer/places2k.txt and I'm sure you can find a list of states somewhere.
Once you have that, here's a simple strategy for an efficient solution:
put the list of cities and states into a hashtable
split the input string (ex. "Califonia John Doe $213 $1232") by spaces
for each prefix of this list, check if the corresponding string is in the hashtable - if it is, then assume that's the state/city and parse the rest of the input accordingly.
Edit: nevermind - you added some information to the question that makes it much easier to solve. It's no longer an efficient string search problem- it's now a simple puzzle to help you practice looping in Java. See Kane's answer.
It's interesting how drastically just a little bit of information can change the scope of a problem :)