How to detect a number in my Linked List of Strings, and get the value - string

I need to sort my Linked List, the problem is that each of my Linked List elements are Strings with sentences. So the question is... how to detect each number in my Linked List and get the value?.
I tried to split my linked list so I can pass trough each element.
private LinkedList<String> list = new LinkedList<String>();
list.add("Number One: 1")
list.add("Number Three: 3")
list.add("Number two:2")
for(Iterator<String> iterator =list.iterator(); iterator.hasNext(); )
{
String string = iterator.next();
for (String word : string.split(" ")){
}
I also tried with "if((word.contains("1") || (word.contains("2")...." inside the for loop, and then pass the value "word" to Double... but I think is not very smart
So my goal is this Output (Number One: 1 , Number Two: 2, Number Three: 3), therefore I need the value of each number first.

why not use tryParse on the string,
for (String word : string.split(" ")){
int outvalue
if(int.TryParse(word, outvalue)){
//DoSomething with result
}
}

Related

Comparing two strings and count differences with Stream API

Today I was trying to compare two strings with Stream API in java.
Let's assume that we have two Strings:
String str1 = "ABCDEFG"
String str2 = "ABCDEEG"
We can make streams from it with:
str1.chars().stream()...
str2.chars().stream()...
And now I want to compare these string, char by char and iterate some variable when char will be different on the same position, so the result in this case will be 1, because there is one difference in this.
I was trying to do call map or forEach from first and there my journey ends, because I don't know how to get corresponding element form second stream.
Assuming that both the strings are of same length(integer max), you can count the differences as :
int diffCount = (int) IntStream.range(0, str1.length())
.filter(i -> str1.charAt(i) != str2.charAt(i)) // corresponding characters from both the strings
.count();
Assuming that both String are of same length, you can use this way too.
long count = IntStream.iterate(0, n-> n+1)
.limit(str1.length()).filter(i -> str1.charAt(i) != str2.charAt(i)).count();

Substring to extract before or/and after specific character in text

I'm currently writing a groovy script that can extract characters based on the condition given, however I struggled extracting specific string after specific number of char. For example:
If (text = 'ABCDEF')
{
Return (start from C and print only CDE)
}
I already used substring but didn't give me the right output:
If (text = 'ABCDEF')
{
Return(text.substring(2));
}
Try this:
if (text == 'ABCDEF')
{
return text.substring(2, 5)
}
= is for assigning a value to a variable.
== is for checking equality between the two variable.
Your capitalization is all out of whack
if (text == 'ABCDEF') {
text.substring(2)
}
There's probably also issues with using return, but that depends on context you haven't shown in your question
Your substring function isn't complete. If you need to grab specific indices (in this case, index 2 to 5), you need to add the index you want to end at. If you don't do that, your string will print the string starting from index 2, and then the remaining characters in the string. You need to need to type this:
if(text == 'ABCDEF') {
return text.substring(2, 5);
}
Also, keep in mind that the end index (index 5) is exclusive, so the character at index 5 won't be printed.

How to find if a string S is contained inside a string made of S inserted at any position in S (only once) itself

As a first check, since a valid input must be made from the insertion of the string into itself, it must be of size twice the string S.
Eg. If S=abc then ababca or aabcbc should return True but False for input such as abcab, abcxa, abcabcabc.
I have already attempted the naive way of check the substring, if it exists then cut out that part and check if the remaining string matches S. But this fails for some type of inputs.
private static void printResult(String s, String p){
int x = p.indexOf(s);
if(x<0){
System.out.println("False");
return;
}
String s1="";
if(p.length()>=s.length()*2){
s1 = p.substring(0,x)+p.substring(x+s.length());
if(s1.equals(s)){
System.out.println("True");
}
else{
System.out.println("False");
}
return;
}
System.out.println("False");
}
Looking at the first occurence of s may not be appropriate in some cases.
Suppose your original word is w=xyx (for x,y some words) then you can insert winto itself to produce xyXYXx (uppercase to show the insertion). Now you can see that if you try to find xyx your algorithm will find it in the first position and then produce yxx as the remaining part.
So you need to look at every possible position before concluding.

Best way to compare multiple string in java

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[].

Lua: how do I split a string (of a varying length) into multiple parts?

I have a string, starting with a number, then a space, then a word of an unknown amount of letters, a space again, and then sometimes another piece of text (which may or may not contain more than one word).
EDIT: the last piece of text is sometimes left out (see example #2)
Using the methods mentioned in the comments, str:find(...) on #2 would return nil.
Example:
"(number) (text) [more text]"
1: "10 HELLO This is a string"
2: "88 BYE"
What I want is to split these strings into a table, inside a table containing more of these split strings, like this:
{
[(number)] = { [1] = (text), [2] = (more text) }
[10] = { [1] = "HELLO", [2] = "This is a string" }
}
I have tried several methods, but none of them give me the desired result.
One of the methods I tried, for example, was splitting the string on whitespaces. But that resulted in:
{
[10] = { [1] = "HELLO", [2] = "This", ... [4] = "string" }
}
Thanks in advance.
Using various Lua string patterns, achieving the desired result is quite easy.
For eg.
function CustomMatching( sVar )
local tReturn = {}
local _, _, iNumber, sWord, sRemain = sVar:find( "^(%d+)%s(%a+)%s(.+)" )
tReturn[tonumber(iNumber)] = { sWord, sRemain }
return tReturn
end
And to call it:
local sVar = "10 HELLO This is a string"
local tMyTable = CustomMatching( sVar )
In the find() method the pattern "^(%d+)%s(%a+)%s(.+)" means:
Find and store all digits(%d) until a space is encountered.
Find and store all letters(%a) until a space is encountered.
Find and store all characters until the end of string is reached.
EDIT
Changed tReturn[iNumber] to tReturn[tonumber(iNumber)] as per the discussion in comments.
You can use the string.match method with an appropriate pattern:
local n, w, str = ('10 HELLO This is a string'):match'^(%d+)%s+(%S+)%s+(.*)$'
your_table[tonumber(n)] = {w, str}

Resources