Related
so I got this task that I need to do and what I am trying to complete is changing a word from a String, to an abbreviation of a word.
The word and an abbreviation is stored in a two dimensional matrix and. Here's the code I already got, but it does not work.
String[][] abriev = {{"United Kingdom", "kilometers"}, {"UK", "km"}};
String origText = "The;coastline;of;United Kingdom;is;12429;kilometers";
int n = origText.length();
for (int i = 0; i < n ; i++){
origText = origText.replaceAll(";", " ");
if (origText.toLowerCase().contains(abriev[i][0])){
origText = origText.replaceAll(abriev[i][0], abriev[0][i]);
}
}
System.out.println(origText);
You're string looks like it's designed to be easily split, and you could iterate over that, do the replacement, and append it to a StringBuilder.
As for the string 2d array, you could easily convert that into a Map and set the key to be the word you're searching for, and the value.
In your code you actually reset the changes you make by calling [0][i] as the second parameter in replaceAll();
What I would do would be this:
String[][] abriev = {{"United Kingdom", "kilometers"}, {"UK", "km"}};
String origText = "The;coastline;of;United Kingdom;is;12429;kilometers";
HashMap<String, String> wordAbbr = new HashMap<String,String>();
for(int i = 0; i < abriev[0].length; i++ )
{
wordAbbr.put(abriev[0][i], abriev[1][i]);
}
String [] origArr = origText.split(";");
String output = "";
for(String s : origArr){
if(wordAbbr.get(s)!=null) {
output = output + " " + wordAbbr.get(s);
}else {
output = output + " " + s;
}
}
output = output + ".";
System.out.println(output);
First of all, I'd convert abriev to a Map for easier lookups. Then, I'd take original text, split it by the ; character, stream it, replace each word with its abbreviation (if available), and re-join the stream:
String[][] abriev = {{"United Kingdom", "kilometers"}, {"UK", "km"}};
Map<String, String> abrievMap =
IntStream.range(0, abriev[0].length)
.boxed()
.collect(Collectors.toMap(i -> abriev[0][i], i -> abriev[1][i]));
String origText = "The;coastline;of;United Kingdom;is;12429;kilometers";
String abbreviated =
Arrays.stream(origText.split(";"))
.map(word -> abrievMap.getOrDefault(word, word))
.collect(Collectors.joining(";"));
You are assigning length of orgText to variable n:
String origText = "The;coastline;of;United Kingdom;is;12429;kilometers";
And you have two dimensional array:
String[][] abriev = {{"United Kingdom", "kilometers"}, {"UK", "km"}};
And you are iterate from 0 to length of origText. Also Inside the loop you are trying to access i'th index, It cannot be done since your first array only contains two indices(two arrays).
Because of that you when you run the program you will get ArrayIndexOutOfBoundsException
Try to use Collections.
I have a String[] and an input String:
String[] ArrayEx = new String[1];
String textInput = "a whole bunch of words"
What I want to do is check if the String contains a word present in the Array, like this.
Ex: textInput = "for example" and ArrayEx[0] = "example"
I know about this method:
Arrays.asList(yourArray).contains(yourValue)
but it checks the full String right? How do I check if the String contains a particular word present in the Array. Even if it is from an ArrayList I have no problem.
Also if yes, can I get that word from the String[]? i.e., in the above case get the String "example".
EDIT:
public void searchNearestPlace(String v2txt)
{
Log.e("TAG", "Started");
v2txt = v2txt.toLowerCase();
String[] places = {"accounting, airport, amusement_park, aquarium, art_gallery, atm, bakery, bank, bar, beauty_salon, bicycle_store, book_store, bowling_alley, bus_station, cafe, campground, car_dealer, car_rental, car_repair, car_wash, casino, cemetery, church, city_hall, clothing_store, convenience_store, courthouse, dentist, department_store, doctor, electrician, electronics_store, embassy, establishment, finance, fire_station, florist, food, funeral_home, furniture_store, gas_station, general_contractor, grocery_or_supermarket, gym, hair_care, hardware_store, health, hindu_temple, home_goods_store, hospital, insurance_agency, jewelry_store, laundry, lawyer, library, liquor_store, local_government_office, locksmith, lodging, meal_delivery, meal_takeaway, mosque, movie_rental, movie_theater, moving_company, museum, night_club, painter, park, parking, pet_store, pharmacy, physiotherapist, place_of_worship, plumber, police, post_office, real_estate_agency, restaurant, roofing_contractor, rv_park, school, shoe_store, shopping_mall, spa, stadium, storage, store, subway_station, synagogue, taxi_stand, train_station, travel_agency, university, veterinary_care, zoo"};
int index;
for(int i = 0; i<= places.length - 1; i++)
{
Log.e("TAG","for");
if(v2txt.contains(places[i]))
{
Log.e("TAG", "sensed?!");
index = i;
}
}
Say v2txt was "awesome airport" the sensed Log never does appear even though all other logs indicate it working
Edit2:
I am so embarrassed that I made such a dunder head mistake. My array is declared wrongly. There should be a " before every ,. I am such a big idiot!
Sorry will change it and let you know.
First of all it has nothing to do with android
Second the solution
boolean flag = false;
String textInput = "for example";
int index = 0;
String[] yourArray = {"ak", "example"};
for (int i = 0; i <= yourArray.length - 1; i++) {
if (textInput.contains(yourArray[i])) {
flag = true;
index = i;
}
}
if (flag)
System.out.println("found at index " + index);
else
System.out.println("not found ");
DEMO
EDIT :
Change your array to
String[] places = {"accounting", "airport", "amusement_park" };
and so on with other values with your array declaration it has one index.
you can split your string and get array of words
txArray = textInput.split(" ");
then for each element in txArray check if
Arrays.asList(ArrayEx).contains(txArray[i])
txArray = "Hello I'm your String";
String[] splitStr = txArray.split(" ");
int i=0;
while(splitStr[i]){
if(Arrays.asList(ArrayEx).contains(txArray[i])){
System.out.println("FOUND");
}
i++;
}
You can use Java - Regular Expressions.
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Testing {
public static void main(String[] args) {
String textInput = "for example";
String[] arrayEx = new String[1];
arrayEx[0] = "example";
Pattern p = Pattern.compile(arrayEx[0]);
Matcher m = p.matcher(textInput);
boolean matchedFoundStatus = false;
while (m.find()) {
matchedFoundStatus = true;
}
System.out.println("matchedFoundStatus:" + matchedFoundStatus);
}
}
Try this;
Sting text2check = "Your Name":
for(int t = 0; t < array.length; t++)
{
if (text2check.equals(array[t])
// Process it Here
break;
}
"How do I check if the String contains a particular word present in the Array?" is the same thing as Is there an element in the array, for which the input string contains this element
Java 8
String[] words = { "example", "hello world" };
String input = "a whole bunch of words";
Arrays.stream(words).anyMatch(input::contains);
(The matching words can also be extracted, if needed:)
Arrays.stream(words)
.filter(input::contains)
.toArray();
If you are stuck with Java 7, you will have to re-implement "anyMatch" and "filter" yourself:
Java 7
boolean anyMatch(String[] words, String input) {
for(String s : words)
if(input.contains(s))
return true;
return false;
}
List<String> filter(String[] words, String input) {
List<String> matches = new ArrayList<>();
for(String s : words)
if(input.contains(s))
matches.add(s);
return matches;
}
This will take an String array, and search through all the strings looking for a specific char sequence found in a string. Also, native Android apps are programmed in the Java language. You might find it beneficial to read up more on Strings.
String [] stringArray = new String[5];
//populate your array
String inputText = "abc";
for(int i = 0; i < stringArray.length; i++){
if(inputText.contains(stringArray[i]){
//Do something
}
}
I've made an String array out of a .txt and now want to make a HashMap with this string as key. But I don't want to have the String as one key to one value, I want to have each Information as a new key for the HashMap.
private static String[] readAndConvertInputFile() {
String str = StdIn.readAll();
String conv = str.replaceAll("\'s", "").replaceAll("[;,?.:*/\\-_()\"\'\n]", " ").replaceAll(" {2,}", " ").toLowerCase();
return conv.split(" "); }
So the information in the string is like ("word", "thing", "etc.", "pp.", "thing").
My value should be the frequency of the word in the text. So for example key: "word" value: 1, key: "thing" value: 2 and so on... I'm clueless and would be grateful if someone could help me, at least with the key. :)
You can create a Map while using the String value at each array index as the key, and an Integer as the value to keep track of how many times a word appeared.
Map<String,Integer> map = new HashMap<String,Integer>();
Then when you want to increment, you can check if the Map already contains the key, if it does, increase it by 1, otherwise, set it to 1.
if (occurences.containsKey(word)) {
occurences.put(word, occurences.get(word) + 1);
} else {
occurences.put(word, 1);
}
So, while you are looping over your string array, convert the String to lower case (if you want to ignore case for word occurrences), and increment the map using the if statement above.
for (String word : words) {
word = word.toLowerCase(); // remove if you want case sensitivity
if (occurences.containsKey(word)) {
occurences.put(word, occurences.get(word) + 1);
} else {
occurences.put(word, 1);
}
}
A full example is shown below. I converted to words to lowercase to ignore case when using the key in the map, if you want to keep case, remove the line where I convert it to lowercase.
public static void main(String[] args) {
String s = "This this the has dog cat fish the cat horse";
String[] words = s.split(" ");
Map<String, Integer> occurences = new HashMap<String, Integer>();
for (String word : words) {
word = word.toLowerCase(); // remove if you want case sensitivity
if (occurences.containsKey(word)) {
occurences.put(word, occurences.get(word) + 1);
} else {
occurences.put(word, 1);
}
}
for(Entry<String,Integer> en : occurences.entrySet()){
System.out.println("Word \"" + en.getKey() + "\" appeared " + en.getValue() + " times.");
}
}
Which will give me output:
Word "cat" appeared 2 times.
Word "fish" appeared 1 times.
Word "horse" appeared 1 times.
Word "the" appeared 2 times.
Word "dog" appeared 1 times.
Word "this" appeared 2 times.
Word "has" appeared 1 times.
Yes, you can use an array (regardless of element type) as a HashMap key.
No, shouldn't do so. The behavior is unlikely to be what you want (in general).
In your particular case, I don't see why you even propose using an array as a key in the first place. You seem to want Strings drawn from among your array elements as keys.
You could construct a word frequency table like so:
Map<String, Integer> computeFrequencies(String[] words) {
Map<String, Integer> frequencies = new HashMap<String, Integer>();
for (String word: words) {
Integer wordFrequency = frequencies.get(word);
frequencies.put(word,
(wordFrequency == null) ? 1 : (wordFrequency + 1));
}
return frequencies;
}
In java 8 using stream
String[] array=new String[]{"a","b","c","a"};
Map<String,Integer> map1=Arrays.stream(array).collect(Collectors.toMap(x->x,x->1,(key,value)->value+1));
I have an arraylist like below
List<String> list = new ArrayList<String>();
list.add("P Pro Rata(Average Cost w/Tax Lots)");
list.add("A apple is good");
list.add("B ball is nice");
list.add("C cat is not there");
I want the first space of each element in the array list should be replaced with : operator(only first space and for each element)
so output should be
A:apple is good
B:ball is nice
C:cat is not there
I have a solution which iterates and creates new element and add it to new list and using that new list
can any one come up with best solution ?
Try this:
for(int i=0;i<list.size();i++) {
list.set(i,list.get(i).replaceFirst(" ", ":"));
}
You can use indexOf to find the first occurance of a space in the strings as such:
for (String s : list) {
int index = s.indexOf(" ");
String prefix = s.substring(0, index);
String suffix = s.substring(index+1);
System.out.println(prefix + ":" + suffix);
}
Use for each to iterate array list and replaceFirst will help you replace first char
int i=0;
for (String s : list){
list.set(i,s.replaceFirst(" ", ":"));
i++;
}
I've searched high and low and finally have to ask.
I have an array containing, for example, ["123456","132457", "468591", ... ].
I have a string with a value of "46891".
How do I search through the array and find the object that contains all the characters from my string value? For example the object with "468591" contains all the digits from my string value even though it's not an exact match because there's an added "5" between the "8" and "9".
My initial thought was to split the string into its own array of numbers (i.e. ["4","6","8","9","1"] ), then to search through the array for objects containing the number, to create a new array from it, and to keep whittling it down until I have just one remaining.
Since this is likely a learning assignment, I'll give you an idea instead of an implementation.
Start by defining a function that takes two strings, and returns true if the first one contains all characters of the second in any order, and false otherwise. It should looks like this:
boolean containsAllCharsInAnyOrder(String str, String chars) {
...
}
Inside the function set up a loop that picks characters ch from the chars string one by one, and then uses str.indexOf(ch) to see if the character is present in the string. If the index is non-negative, continue; otherwise, return false.
If the loop finishes without returning, you know that all characters from chars are present in src, so you can return true.
With this function in hand, set up another loop in your main function to go through elements of the array, and call containsAllCharsInAnyOrder on each one in turn.
I think you can use sets for this.
List<String> result = new ArrayList<>();
Set<String> chars = new HashSet<>(Arrays.asList(str.split(""));
for(String string : stringList) {
Set<String> stringListChars = new HashSet<>(Arrays.asList(string.split(""));
if(chars.containsAll(stringListChars)) {
result.add(string);
}
}
There is a caveat here; it doesn't work as you would expect for repeated characters and you haven't specified how you want to handle that (for example, 1154 compared against 154 will be considered a positive match). If you do want to take into account repeated characters and you want to make sure that they exist in the other string, you can use a List instead of a Set:
List<String> result = new ArrayList<>();
List<String> chars = Arrays.asList(str.split(""));
for(String string : stringList) {
List<String> stringListChars = Arrays.asList(string.split("");
if(chars.containsAll(stringListChars)) {
result.add(string);
}
}
Your initial idea was good start, so what you can do is to create not an array but set, then using Guava Sets#powerSet method to create all possible subsets filter only those that have "46891".length mebers, convert each set into String and look those strings in the original array :)
You could do this with the ArrayList containsAll method along with asList:
ArrayList<Character> lookingForChars = new ArrayList<Character>(Arrays.asList(lookingForString.toCharArray()));
for (String toSearchString : array) {
ArrayList<Character> toSearchChars = new ArrayList<Character>(Arrays.asList(toSearchString.toCharArray));
if (toSearchChars.containsAll(lookingForChars)) {
System.out.println("Match Found!");
}
}
You can use String#chartAt() in a nested for loop to compare your string with each of the array's elements.
This method would help you check whether a character is contained in both strings.
This is more tricky then a straigt-forward solution.
The are better algorithms but here one easy to implement and understand.
Ways of solving:
Go through every char at your given string and check if it at the
given arrray.
Collect list for every string from the selected
array containing the given char.
Check if no other char to check.
If there is, Perform A again but on the collected list(result list).
Else, Return all possible matches.
try this
public static void main(String args[]) {
String[] array = {"123456", "132457", "468591"};
String search = "46891";
for (String element : array) {
boolean isPresent = true;
for (int index = 0; index < search.length(); index++) {
if(element.indexOf(search.charAt(index)) == -1){
isPresent = false;
break;
}
}
if(isPresent)
System.out.println("Element "+ element + " Contains Serach String");
else
System.out.println("Element "+ element + " Does not Contains Serach String");
}
}
This sorts the char[]'s of the search string and the and the string to search on. Pretty sure (?) this is O(n logn) vs O(n^2) without sorting.
private static boolean contains(String searchMe, String searchOn){
char[] sm = searchMe.toCharArray();
Arrays.sort(sm);
char[] so = searchOn.toCharArray();
Arrays.sort(so);
boolean found = false;
for(int i = 0; i<so.length; i++){
found = false; // necessary to reset 'found' on subsequent searches
for(int j=0; j<sm.length; j++){
if(sm[j] == so[i]){
// Match! Break to the next char of the search string.
found = true;
break;
}else if(sm[j] > so[i]){ // No need to continue because they are sorted.
break;
}
}
if(!found){
// We can quit here because the arrays are sorted.
// I know if I did not find a match of the current character
// for so in sm, then no other characters will match because they are
// sorted.
break;
}
}
return found;
}
public static void main(String[] args0){
String value = "12345";
String[] testValues = { "34523452346", "1112", "1122009988776655443322",
"54321","7172839405","9495929193"};
System.out.println("\n Search where order does not matter.");
for(String s : testValues){
System.out.println(" Does " + s + " contain " + value + "? " + contains(s , value));
}
}
And the results
Search where order does not matter.
Does 34523452346 contain 12345? false
Does 1112 contain 12345? false
Does 1122009988776655443322 contain 12345? true
Does 54321 contain 12345? true
Does 7172839405 contain 12345? true
Does 9495929193 contain 12345? true