Best way to compare multiple string in java - string

Suppose I have a string "That question is on the minds of every one.".
I want to compare each word in string with a set of word I.e. (to , is ,on , of) and if those word occurs I want to append some string on the existing string.
Eg.
to = append "Hi";
Is = append "Hello";
And so on.
To be more specific I have used StringTokenizer to get the each word and compared thru if else statement. However we can use Switch also but it is available in Jdk 1.
7.

I don't know if this is what you mean, but:
You could use String.split() to separate the words from your string like
String[] words = myString.split(" ");
and then, for each word, compare it with the given set
for(String s : words)
{
switch(s)
{
case("to"):
[...]
}
}
Or you could just use the String.contains() method without even splitting your string, but I don't know if that's what you wanted.

Use a HashMap<String,String> variable to store your set of words and the replacement words you want. Then split your string with split(), loop through the resulting String[] and for each String in the String[], check whether the HashMap containsKey() that String. Build your output/resulting String in the loop - if the word is contained in the HashMap, replace it with the value of the corresponding key in the HashMap, otherwise use the String you are currently on from the String[].

Related

Need to extract the last word in a Rust string

I am doing some processing of a string in Rust, and I need to be able to extract the last set of characters from that string. In other words, given a string like the following:
some|not|necessarily|long|name
I need to be able to get the last part of that string, namely "name" and put it into another String or a &str, in a manner like:
let last = call_some_function("some|not|necessarily|long|name");
so that last becomes equal to "name".
Is there a way to do this? Is there a string function that will allow this to be done easily? If not (after looking at the documentation, I doubt that there is), how would one do this in Rust?
While the answer from #effect is correct, it is not the most idiomatic nor the most performant way to do it. It'll walk the entire string and match all of the |s to reach the last. You can make it better, but there is a method of str that does exactly what you want - rsplit_once():
let (_, name) = s.rsplit_once('|').unwrap();
// Or
// let name = s.rsplit_once('|').unwrap().1;
//
// You can also use a multichar separator:
// let (_, name) = s.rsplit_once("|").unwrap();
// But in the case of a single character, a `char` type is likely to be more performant.
Playground.
You can use the String::split() method, which will return an iterator over the substrings split by that separator, and then use the Iterator::last() method to return the last element in the iterator, like so:
let s = String::from("some|not|necessarily|long|name");
let last = s.split('|').last().unwrap();
assert_eq!(last, "name");
Please also note that string slices (&str) also implement the split method, so you don't need to use std::String.
let s = "some|not|necessarily|long|name";
let last = s.split('|').last().unwrap();
assert_eq!(last, "name");

JS QUESTION: how can i make it so that when im detecting a word inside a string, i check standalone words like Hello

How do i check for the word "Hello" inside a string in an if statement but it should only detect if the word "Hello" is alone and not like "Helloo" or "HHello"
The easiest way to do such thing is to use regular expressions. By using regular expressions you can define a rule in order to validate a specific pattern.
Here is the rule for the pattern you required to be matched:
The word must contain the string "hello"
The string "hello" must be preceded by white-space, otherwise it must be the found at the beginning of the string to be matched.
The string "hello" must be followed by either a '.' or a white-space, Otherwise it must be found at the end of the string to be matched.
Here is a simple js code which implements the above rule:
let string = 'Hello, I am hello. Say me hello.';
const pattern = /(^|\s)hello(\s|.|$)/gi;
/*const pattern = /\bhello\b/ you can use this pattern, its easier*/
let matchResult = string.match(pattern);
console.log(matchResult);
In the above code I assumed that the pattern is not case sensitive. That is why I added case insensitive modifier ("i") after the pattern. I also added the global modifier ("g") to match all occurrence of the string "hello".
You can change the rule to whatever you want and update the regular expression to confirm to the new rule. For example you can allow for the string to be followed by "!". You can do that by simply adding "|!" after "$".
If you are new to regular expressions I suggest you to visit W3Schools reference:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
One way to achieve this is by first replacing all the non alphabetic characters from string like hello, how are you #NatiG's answer will fail at this point, because the word hello is present with a leading , but no empty space. once all the special characters are removed you can simply split the string to array of words and filter 'hello' from there.
let text = "hello how are you doing today? Helloo HHello";
// Remove all non alphabetical charachters
text = text.replace(/[^a-zA-Z0-9 ]/g, '')
// Break the text string to words
const myArray = text.split(" ");
const found = myArray.filter((word) => word.toLowerCase() == 'hello')
// to check the array of found ```hellos```
console.log(found)
//Get the found status
if(found.length > 0) {
console.log('Found')
}
Result
['hello']
Found

How to modify the value of a Hashmap, which has key&value as Strings,and the 'value' is a single string consisting of comma separated values

I am trying to modify a Hashmap .
The 'value' is a single string consisting of comma separated values.
(for e.g.: "aid=abc,bid=def,cid=gh2")
I need to replace particular values from them with a corresponding value from the DB.
(for e.g. changing the bid to 123, which would result in the above 'value' string as: "aid=abc,bid=123,cid=gh2")
And then set the modified 'value' to the corresponding key, so that the hashmap consists of modified values.
I tried to iterate through the keys , and with map(key) which will give the value, I tried to convert that to a list of comma separated values and then iterate through that list, and in each of the string, if I find 'bid'(example string above), then I do the necessary manipulation and then set it back to the Hashmap(which I Wasnt able to do since Strings arent mutable)
for (String name :outputMap.keySet())
List urlList = Arrays.asList(outputMap.get(name).split(",")); for(int i=0;i
expected result:"aid=abc,bid=123,cid=gh2" (post the manipulation)
actual result: unable to do.
I have used Stringbuffer for issues where string had to be modified, but was a little apprehensive to use that here, since this has already multiple conversions going.
The code needs to Java 7 compliant, since this is being deployed in a Client machine still using some legacy environment.(They are scheduled to migrate to java 8 , but thats scheduled for much later)
Any assistance here would be appreciated.
static Map<String, String> replace(Map<String, String> map, String toReplace, String replacement) {
return map.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey,
e -> transformValue(e.getValue(), toReplace, replacement)));
}
static String transformValue(String value, String toReplace, String replacement) {
return Arrays.stream(value.split(","))
.map(pair -> pair.split("="))
.map(sPair -> sPair[0] + "=" + (toReplace.equals(sPair[0]) ? replacement : sPair[1]))
.collect(Collectors.joining(","));
}
this will iterate through all entries of map and create a new map with changed values. Example:
var map = Map.of("key1", "aid=abc,bid=def,cid=gh2");
System.out.println(replace(map, "bid", "123").get("key1"));
will print aid=abc,bid=123,cid=gh2

In Swift how to obtain the "invisible" escape characters in a string variable into another variable

In Swift I can create a String variable such as this:
let s = "Hello\nMy name is Jack!"
And if I use s, the output will be:
Hello
My name is Jack!
(because the \n is a linefeed)
But what if I want to programmatically obtain the raw characters in the s variable? As in if I want to actually do something like:
let sRaw = s.raw
I made the .raw up, but something like this. So that the literal value of sRaw would be:
Hello\nMy name is Jack!
and it would literally print the string, complete with literal "\n"
Thank you!
The newline is the "raw character" contained in the string.
How exactly you formed the string (in this case from a string literal with an escape sequence in source code) is not retained (it is only available in the source code, but not preserved in the resulting program). It would look exactly the same if you read it from a file, a database, the concatenation of multiple literals, a multi-line literal, a numeric escape sequence, etc.
If you want to print newline as \n you have to convert it back (by doing text replacement) -- but again, you don't know if the string was really created from such a literal.
You can do this with escaped characters such as \n:
let secondaryString = "really"
let s = "Hello\nMy name is \(secondaryString) Jack!"
let find = Character("\n")
let r = String(s.characters.split(find).joinWithSeparator(["\\","n"]))
print(r) // -> "Hello\nMy name is really Jack!"
However, once the string s is generated the \(secondaryString) has already been interpolated to "really" and there is no trace of it other than the replaced word. I suppose if you already know the interpolated string you could search for it and replace it with "\\(secondaryString)" to get the result you want. Otherwise it's gone.

Algorithms for "shortening" strings?

I am looking for elegant ways to "shorten" the (user provided) names of object. More precisely:
my users can enter free text (used as "name" of some object), they can use up to 64 chars (including whitespaces, punctuation marks, ...)
in addition to that "long" name; we also have a "reduced" name (exactly 8 characters); required for some legacy interface
Now I am looking for thoughts on how to generate these "reduced" names, based on the 64-char name.
With "elegant" I am wondering about any useful ideas that "might" allow the user to recognize something with value within the shortened string.
Like, if the name is "Production Test Item A5"; then maybe "PTIA5" might (or might not) tell the user something useful.
Apply a substring method to the long version, trim it, in case there are any whitespace characters at the end, optionally remove any special characters from the very end (such as dashes) and finally add a dot, in case you want to indicate your abbreviation that way.
Just a quick hack to get you started:
String longVersion = "Aswaghtde-5d";
// Get substring 0..8 characters
String shortVersion = longVersion.substring(0, (longVersion.length() < 8 ? longVersion.length() : 8));
// Remove whitespace characters from end of String
shortVersion = shortVersion.trim();
// Remove any non-characters from end of String
shortVersion = shortVersion.replaceAll("[^a-zA-Z0-9\\s]+$", "");
// Add dot to end
shortVersion = shortVersion.substring(0, (shortVersion.length() < 8 ? shortVersion.length() : shortVersion.length() - 1)) + ".";
System.out.println(shortVersion);
I needed to shorten names to function as column names in a database. Ideally, the names should be recognizable for users. I set up a dictionary of patterns for commonly occuring words with corresponding "abbreviations". This was applied ONLY to those names which were over the limit of 30 characters.

Resources