Replacing words in a String by letters - string

I've got this string :
var str:String = mySharedObject.data.theDate;
where mySharedObject.data.theDate can contain the word January, February, March..etc (depends on which button the user clicked).
Is it possible to tell to my code to replace "January" by "1" (if mySharedObject contain the word January), "February" by "2"...etc ?

The most basic way to do what you'd like, is to the use the replace method of a string.
str = str.replace("January","1");
Now, you could repeat or chain together for all 12 months (eg str = str.replace("January","1").replace("February","2").replace("March","3")..etc) or you could do it in a loop:
//have an array of all 12 months in order
var months:Array = ["January","February","March","April","May"]; //etc
//create a function to replace all months with the corresponding number
function swapMonthForNumber(str:String):String {
//do the same line of code for every item in the array
for(var i:int=0;i<months.length;i++){
//i is the item, which is 0 based, so we have to add 1 to make the right month number
str = str.replace(months[i],String(i+1));
}
//return the updated string
return str;
}
var str:String = swapMonthForNumber(mySharedObject.data.theDate);
Now, there are a few other ways to replace strings in ActionScript that are all a little different in terms of complexity and performance, but if you're just getting started I would stick with the replace method.
The only possible caveat with replace is that it only replaces the first instance of the word, so if your string was "January January January", it would come out as "1 January January".

Related

Haxe: How do I repeat a string n times

I want to repeat a character or string, such as "Z", a specific number of times (let's say 5 times). I could easily do it in a loop, of course, like this:
var combined = "";
for(i in 0...5) {
combined += "Z";
}
trace(combined); // ZZZZZ
But is there a function in the standard library, or a some kind of special syntax sugar, that would allow me to do it as a one liner?
There are a couple of ways it could be done in a one-liner.
From the standard library, you could call StringTools.rpad() or StringTools.lpad(), starting with an empty string:
var combined = StringTools.rpad("", "Z", 5);
You could use Array comprehension to add the character to an array n times, and then call Array.join() with an empty string as the separator:
var combined = [for (i in 0...5) "Z"].join("");

Lua string to table

I have a string that I need to read as a table
notes = "0,5,10,16"
so if I need the 3rd value of the current notes that is 10
value = notes[3]
If you trust the strings, you can reuse the Lua parser:
notes = "0,5,10,16"
notes = load("return {"..notes.."}")()
print(notes[3])
For the example string, you can just do
local notes_tab = {}
for note in notes:gmatch("%d*") do
table.insert(notes_tab, tonumber(note))
end
We can change the __index metamethod of all strings to return the nth element separated by commas. Doing this, however, gives the problem that we cannot do something like notes:gmatch(",?1,?") anymore. See this old StackOverflow post. It can be solved, by checking whether the __index is called with a string or other value.
notes = "0,5,10,16"
getmetatable("").__index = function(str, key)
if type(key) == "string" then
return string[key]
else
next_value = string.gmatch(str, "[^,]+")
for i=1, key - 1 do
next_value()
end
return next_value()
end
end
print(notes[3]) --> 10
string.gmatch returns a function over which we can iterate, so calling this n times will result in the nth number being returned.
The for loop makes sure that all the numbers before which we want have been iterated over by the gmatch.
Depending on what you want to do with the numbers you can either return it as a string or convert it to a number immediately.

find number of repeating substrings in a string

I am looking for an algorithm that will find the number of repeating substrings in a single string.
For this, I was looking for some dynamic programming algorithms but didn't find any that would help me. I just want some tutorial on how to do this.
Let's say I have a string ABCDABCDABCD. The expected output for this would be 3, because there is ABCD 3 times.
For input AAAA, output would be 4, since A is repeated 4 times.
For input ASDF, output would be 1, since every individual character is repeated 1 time only.
I hope that someone can point me in the right direction. Thank you.
I am taking the following assumptions:
The repeating substrings must be consecutive. That is, in case of ABCDABC, ABC would not count as a repeating substring, but it would in case of ABCABC.
The repeating substrings must be non-overalpping. That is, in case of ABCABC, ABC would not count as a repeating substring.
In case of multiple possible answers, we want the one with the maximum value. That is, in the case of AAAA, the answer should be 4 (a is the substring) rather than 2 (aa is the substring).
Under these assumptions, the algorithm is as follows:
Let the input string be denoted as inputString.
Calculate the KMP failure function array for the input string. Let this array be denoted as failure[]. This operation if of linear time complexity with respect to the length of the string. So, by definition, failure[i] denotes the length of the longest proper-prefix of the substring inputString[0....i] that is also a proper-suffix of the same substring.
Let len = inputString.length - failure.lastIndexValue. At this point, we know that if there is any repeating string at all, then it has to be of this length len. But we'll need to check for that; First, just check if len perfectly divides inputString.length (that is, inputString.length % len == 0). If yes, then check if every consecutive (non-overlapping) substring of len characters is the same or not; this operation is again of linear time complexity with respect to the length of the input string.
If it turns out that every consecutive non-overlapping substring is the same, then the answer would be = inputString.length/ len. Otherwise, the answer is simply inputString.length, as there is no such repeating substring present.
The overall time complexity would be O(n), where n is the number of characters in the input string.
A sample code for calculating the KMP failure array is given here.
For example,
Let the input string be abcaabcaabca.
Its KMP failure array would be - [0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8].
So, our len = (12 - 8) = 4.
And every consecutive non-overlapping substring of length 4 is the same (abca).
Therefore the answer is 12/4 = 3. That is, abca is repeated 3 times repeatedly.
The solution for this with C# is:
class Program
{
public static string CountOfRepeatedSubstring(string str)
{
if (str.Length < 2)
{
return "-1";
}
StringBuilder substr = new StringBuilder();
// Length of the substring cannot be greater than half of the actual string
for (int i = 0; i < str.Length / 2; i++)
{
// We will iterate through half of the actual string and
// create a new string by appending the current character to the previous character
substr.Append(str[i]);
String clearedOfNewSubstrings = str.Replace(substr.ToString(), "");
// We will remove the newly created substring from the actual string and
// check if the length of the actual string, cleared of the newly created substring, is 0.
// If 0 it tells us that it is only made of its substring
if (clearedOfNewSubstrings.Length == 0)
{
// Next we will return the count of the newly created substring in the actual string.
var countOccurences = Regex.Matches(str, substr.ToString()).Count;
return countOccurences.ToString();
}
}
return "-1";
}
static void Main(string[] args)
{
// Input: {"abcdaabcdaabcda"}
// Output: 3
// Input: { "abcdaabcdaabcda" }
// Output: -1
// Input: {"barrybarrybarry"}
// Output: 3
var s = "asdf"; // Output will be -1
Console.WriteLine(CountOfRepeatedSubstring(s));
}
}
How do you want to specify the "repeating string"? Is it simply the first group of characters up until either a) the first character is found again, b) the pattern begins to repeat, or c) some other criteria?
So, if your string is "ABBAABBA", is that a 2 because "ABBA" repeats twice or is it 1 because you have "ABB" followed by "AAB"? What about "ABCDABCE" -- does "ABC" count (despite the "D" in between repetitions?) In "ABCDABCABCDABC", is the repeating string "ABCD" (1) or "ABCDABC" (2)?
What about "AAABBAAABB" -- is that 3 ("AAA") or 2 ("AAABB")?
If the end of the repeating string is another instance of the first letter, it's pretty simple:
Work your way through the string character by character, putting each character into another variable as you go, until the next character matches the first one. Then, given the length of the substring in your second variable, check the next bit of your string to see if it matches. Continue until it doesn't match or you hit the end of the string.
If you just want to find any length pattern that repeats regardless of whether the first character is repeated within the pattern, it gets more complicated (but, fortunately, it's the sort of thing computers are good at).
You'll need to go character by character building a pattern in another variable as above, but you'll also have to watch for the first character to reappear and start building a second substring as you go, to see if it matches the first. This should probably go in an array as you might encounter a third (or more) instance of the first character which would trigger the need to track yet another possible match.
It's not difficult but there is a lot to keep track of and it's a rather annoying problem. Is there a particular reason you're doing this?

Extracting a specific word and a number of tokens on each side of it from each string in a column in SAS?

Extracting a specific word and a number of tokens on each side of it from each string in a column in SAS EG ?
For example,
row1: the sun is nice
row2: the sun looks great
row3: the sun left me
Is there a code that would produce the following result column (2 words where sun is the first):
SUN IS
SUN LOOKS
SUN LEFT
and possibly a second column with COUNT in case of duplicate matches.
So if there was 20 SUN LOOKS then it they would be grouped and have a count of 20.
Thanks
I think you can use functions findw() and scan() to do want you want. Both of those functions operate on the concept of word boundaries. findw() returns the position of the word in the string. Once you know the position, you can use scan() in a loop to get the next word or words following it.
Here is a simple example to show you the concept. It is by no means a finished or polished solution, but intended you point you in the right direction. The input data set (text) contains the sentences you provided in your question with slight modifications. The data step finds the word "sun" in the sentence and creates a variable named fragment that contains 3 words ("sun" + the next 2 words).
data text2;
set text;
length fragment $15;
word = 'sun'; * search term;
fragment_len = 3; * number of words in target output;
word_pos = findw(sentence, word, ' ', 'e');
if word_pos then do;
do i = 0 to fragmen_len-1;
fragment = catx(' ', fragment, scan(sentence, word_pos+i));
end;
end;
run;
Here is a partial print of the output data set.
You can use a combination of the INDEX, SUBSTR and SCAN functions to achieve this functionality.
INDEX - takes two arguments and returns the position at which a given substring appears in a string. You might use:
INDEX(str,'sun')
SUBSTR - simply returns a substring of the provided string, taking a second numeric argument referring to the starting position of the substring. Combine this with your INDEX function:
SUBSTR(str,INDEX(str,'sun'))
This returns the substring of str from the point where the word 'sun' first appears.
SCAN - returns the 'words' from a string, taking the string as the first argument, followed by a number referring to the 'word'. There is also a third argument that specifies the delimiter, but this defaults to space, so you wouldn't need it in your example.
To pick out the word after 'sun' you might do this:
SCAN(SUBSTR(str,INDEX(str,'sun')),2)
Now all that's left to do is build a new string containing the words of interest. That can be achieved with concatenation operators. To see how to concatenate two strings, run this illustrative example:
data _NULL_;
a = 'Hello';
b = 'World';
c = a||' - '||b;
put c;
run;
The log should contain this line:
Hello - World
As a result of displaying the value of the c variable using the put statement. There are a number of functions that can be used to concatenate strings, look in the documentation at CAT,CATX,CATS for some examples.
Hopefully there is enough here to help you.

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