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);
}
Related
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.
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.
I have this string:
Some text: $ 12.3 9
I want to get as a result:
12.39
I have found examples on how to keep only numbers, but here I am wanting to keep the decimal point "."
What's a good way to do this in Swift?
This should work (it's a general approach to filtering on a set of characters) :
[EDIT] simplified and adjusted to Swift3
[EDIT] adjusted to Swift4
let text = "$ 123 . 34 .876"
let decimals = Set("0123456789.")
var filtered = String( text.filter{decimals.contains($0)} )
If you need to ignore anything past the second decimal point add this :
filtered = filtered.components(separatedBy:".") // separate on decimal point
.prefix(2) // only keep first two parts
.joined(separator:".") // put parts back together
Easiest and simplest reusable way: you can use this regex replacement option. This replaces all characters except 0 to 9 and dot (.) .
let yourString = "$123. 34"
//pattern says except digits and dot.
let pattern = "[^0-9.]"
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
//replace all not required characters with empty string ""
let string_With_Just_Numbers_You_Need = regex.stringByReplacingMatchesInString(yourString, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, yourString.characters.count), withTemplate: "")
//your number converted to Double
let convertedToDouble = Double(string_With_Just_Numbers_You_Need)
} catch {
print("Cant convert")
}
One possible solution to the question follows below. If you're working with text fields and currency, however, I suggest you take a look at the thread Leo Dabus linked to.
extension String {
func filterByString(myFilter: String) -> String {
return String(self.characters.filter {
myFilter.containsString(String($0))
})
}
}
var a = "$ 12.3 9"
let myFilter = "0123456789.$"
print(a.filterByString(myFilter)) // $12.39
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".
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
}
}