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

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.

Related

Check if a substring exists at the beginning, middle and end of a string while allowing intersections

It sound easy, you can simply iterate and check them, but the problem here is optimization: Don't make any needless checking, needless new objects or operation.
The algorithm will be tested against a huge set of test cases to verify its efficiency.
Examples:
"aaaa" contains "aa" at the beginning, middle and end.
"baabaabaaaabbaab" contains "baab" at the beginning, middle and end. See the intersection.
And one more thing I forgot to say:
You are not given the substring to check for, you need to find if such a substring exists, if it doesn't return false, if it does return true.
Find the longest substring satisfying those conditions and return it, or print it (your choice).
A simple Boolean function, right?
Update:
The substring needs to be at least 2 character shorter that the main string.
Sorry, it was my mistake in the "aaa" example, I fixed it.
You can solve it with KMP, a string matching algorithm. Using it to generate an array fail[]
fail[i] = max {k | S[1:k] == S[i-k+1:i]}
Then you can enumerate all possible value of fail[n](fail[n], fail[ fail[n] ], fail[ fail[fail[n]] ] ...) to check whether it exists in the middle.
The complexity is O(n).
Let's jump the shark:
function the_best_match_at_the_beginning_the_middle_and_the_end( s ){
print( s );
return true;
}
That's one of these "you might get significantly better in terms of theoretical complexity, but in reality, linear operation is always faster" answers:
Assuming in is your input string, pattern is what you're looking for, and you're able to read or look up C-standard-lib-style methods like strncmp. Let l_in be the number of characters in the input, l_pattern the number of characters in the pattern.
Simply explicitely check the start (strncmp(in,pattern,l_pattern)); then use a bog-normal linear search from the second letter on (strstr(in+1, pattern):
If strstr didn't find anything, there's no middle match nor a end match.
If it's at the end (result of strstr is l_in-l_pattern), you've got no middle match.
If it's not found at the end, you've got a middle match. Manually check (strncmp(in+l_in-l_patter, pattern, l_pattern)) for the end match.
Why this is faster? Because modern computers are pretty optimized for searching through data linearly, see Bjarne "C++" Stroustrup's why you should avoid linked lists. Simply put, letting your CPU run on a continous amount of memory prefetched to a CPU cache is much much faster than being "clever" about avoiding a few duplicate checks.
One clean way to approach this is to just check all substrings in the input from the beginning. Compare each substring to see that it exists at the end, and then check to see if it exists in the middle. For the middle check, you can compare against the input string with its first and last characters removed.
public boolean subStrings(String input) {
if (input == null || input.equals("")) {
return false;
}
if (input.length() == 1) {
System.out.println(input + " is a match!");
return true;
}
boolean foundIt = false;
String longestMatch = "";
for (int i=1; i < inputNew.length(); ++i) {
String substring = inputNew.substring(0, i);
boolean endMatch = inputNew.substring(inputNew.length()-i, inputNew.length()).equals(substring);
boolean midMatch = inputNew.substring(1, inputNew.length()-1).contains(substring);
if (endMatch && midMatch) {
longestMatch = substring;
foundIt = true;
}
}
if (foundIt) {
System.out.println(longestMatch + " is a match!");
return true;
}
else {
return false;
}
}
subStrings("baabaabaaaabbaab");
Output:
baab is a match!

How to compare upper and lowercase letters in a conditional in Swift

Apologies if this is a duplicate. I have a helper function called inputString() that takes user input and returns a String. I want to proceed based on whether an upper or lowercase character was entered. Here is my code:
print("What do you want to do today? Enter 'D' for Deposit or 'W' for Withdrawl.")
operation = inputString()
if operation == "D" || operation == "d" {
print("Enter the amount to deposit.")
My program quits after the first print function, but gives no compiler errors. I don't know what I'm doing wrong.
It's important to keep in mind that there is a whole slew of purely whitespace characters that show up in strings, and sometimes, those whitespace characters can lead to problems just like this.
So, whenever you are certain that two strings should be equal, it can be useful to print them with some sort of non-whitespace character on either end of them.
For example:
print("Your input was <\(operation)>")
That should print the user input with angle brackets on either side of the input.
And if you stick that line into your program, you'll see it prints something like this:
Your input was <D
>
So it turns out that your inputString() method is capturing the newline character (\n) that the user presses to submit their input. You should improve your inputString() method to go ahead and trim that newline character before returning its value.
I feel it's really important to mention here that your inputString method is really clunky and requires importing modules. But there's a way simpler pure Swift approach: readLine().
Swift's readLine() method does exactly what your inputString() method is supposed to be doing, and by default, it strips the newline character off the end for you (there's an optional parameter you can pass to prevent the method from stripping the newline).
My version of your code looks like this:
func fetchInput(prompt: String? = nil) -> String? {
if let prompt = prompt {
print(prompt, terminator: "")
}
return readLine()
}
if let input = fetchInput("Enter some input: ") {
if input == "X" {
print("it matches X")
}
}
the cause of the error that you experienced is explained at Swift how to compare string which come from NSString. Essentially, we need to remove any whitespace or non-printing characters such as newline etc.
I also used .uppercaseString to simplify the comparison
the amended code is as follows:
func inputString() -> String {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
let str: String = (NSString(data: inputData, encoding: NSUTF8StringEncoding)?.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()))!
return str
}
print("What do you want to do today? Enter 'D' for Deposit or 'W' for Withdrawl.")
let operation = inputString()
if operation.uppercaseString == "D" {
print("Enter the amount to deposit.")
}

How to check if word is the last word in a string?

I would like to check if a specific word is the last one in a string. (the string is the user input from a textfield)
What is a good way to do that?
I would use lastIndexOf():
function endsWith(str:String, ending:String):Boolean {
var index:int = str.lastIndexOf(ending)
return index > -1 && index == str.length - ending.length;
}
trace(endsWith("Hello World", "World"))
/yourword$/.test(string) is the regex pattern to test if a string ends with a specific value.
Please read documentation. [http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00001551.html]
searchString.lastIndexOf("TheWord");

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

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
}
}

Actionscript 3 replacing string

I am trying to replace a substring in a string. My code below replaces all occurrences of substring. E.g. When clicked on in it replaces both in. But I like to replace only clicked one. How can we do this?
The books are in the table in my room.
function correct(e:TextEvent):void{
str =String(e.currentTarget.htmlText);
if(e.text==replacements[e.currentTarget.name]){
e.currentTarget.htmlText =strReplace(str, e.text, corrections[e.currentTarget.name]);
}
}
function strReplace(str:String, search:String, replace:String):String {
return str.split(search).join(replace);
}
You can use TextField.getCharIndexAtPoint(x:Number, y:Number):int to get the (0-based) index of the char in a particular coordinate.
You obviously need to use your clicked point as (x, y).
You can use localX and localY from TextField.click event.
See here for more: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/TextField.html#getCharIndexAtPoint%28%29
At this point you need to search the string to replace in the neighborhood of the clicked char.
For example, something like this:
stringToReplace = "in";
len = stringToReplace.Length;
neighborhood = TextField.substring(clickedCharIndex-len, clickedCharIndex+len);
if (neighborhood.indexOf(stringToReplace)) {
neighborhood = neighborhood.replace(stringToReplace, replacement);
TextField.text = TextField.text(0, clickedCharIndex-len) + neighborhood +
TextField.text(clickedCharIndex+len);
}

Resources