Replace all spaces in a string with + - string

I have a string and I want to replace every space in this string with a + I tired this by using:
tw.Text = strings.Replace(tw.Text, " ", "+", 1)
But that didn't worked for me...any solutions?
For example the string could look like:
The answer of the universe is 42

Use strings.ReplaceAll
tw.Text = strings.ReplaceAll(tw.Text, " ", "+")
If you're using an older version of go (< 1.12), use strings.Replace with -1 as limit (infinite)
tw.Text = strings.Replace(tw.Text, " ", "+", -1)

Documentation on strings.Replace(): http://golang.org/pkg/strings/#Replace
According to the documentation, the fourth integer parameter is the number of replacements. Your example would only replace the first space with a "+". You need to use a number less than 0 for it to not impose a limit:
tw.Text = strings.Replace(tw.Text, " ", "+", -1)

If you are using this in a query, the QueryEscape method provided by net/url is the best solution: https://golang.org/pkg/net/url/#QueryEscape
import "net/url"
tw.Text = url.QueryEscape(tw.Text)

Related

Condition Inside string Concatenation VB.NET

In PHP you can have conditions (if/else) inside a string concatenation.
$string= 'X is' . ($x >0 1 ? ' > 10 ': ' < 10 ')';
Is this same thing possible in VB.NET?
You can use string inpterpolation and the If-operator:
Dim result = $"X is {If(x > 10, " > 10 ", " <= 10 ")}"
Which is syntactic sugar for String.Format:
Dim result = String.Format("X is {0}", If(x > 10, " > 10 ", " <= 10 "))
Yes, with string interpolation you can use expressions - Interpolated Strings
Dim text = $"IsPositive = {If(number > 0, "true", "false"}"
An interpolated string expression creates a string by replacing the
contained expressions with the ToString represenations of the
expressions’ results
The VB equivalent of the ternary operator is the If operator (as distinct from the If statement).
You can translate your code directly from php to VB:
Dim test = "X is" & If(x > 10, " > 10 ", " < 10 ")
(I made some corrections for apparent errors in the source, but I'm not familiar with php so I may have inadvertently introduced differences in behavior.)

String sub not working correctly

I've got yet another question about lua. I've created a method to calculate the total amount of some prices. The prices are in this format: £500. So to convert them to numbers I'm using string:sub() and tonumber(), but I'm getting some weird results. Here is my code:`
function functions.calculateTotalAmount()
print("calculating total amount")
saveData.totalAmount = 0
print("There are " .. #saveData.amounts .. " in the amount file")
for i=1, #saveData.names do
print("SaveData.amounts[" .. i .. "] original = " .. saveData.amounts[i])
print("SaveData.amounts[" .. i .. "] after sub= " .. saveData.amounts[i]:sub(2))
print("totalAmount: " .. saveData.totalAmount)
if saveData.income[i] then
saveData.totalAmount = saveData.totalAmount + tonumber(saveData.amounts[i]:sub(2))
else
saveData.totalAmount = saveData.totalAmount - tonumber(saveData.amounts[i]:sub(2))
end
end
totalAmountStr.text = saveData.totalAmount .. " " .. currencyFull
loadsave.saveTable(saveData, "payMeBackTable.json")
end
I printed out some info in the for loop to determine the problem and this is what is being printed for the first 2 print statements in the for loop:
16:03:51.452 SaveData.amounts1 original = ¥201
16:03:51.452 SaveData.amounts1 after sub= 201
It looks fine here in stackoverflow but for the the ¥ is actually not gone in my log, instead it is replaced with a weird rectangle symbol. There will be a picture of the printed text attached to this post.
Does anyone see what is going on here?
Don't use sub in this case as the ¥ sign is likely a multi-byte sequence (depending on the encoding), so using sub(2) you are cutting it in the middle instead of removing it.
Use gsub("[^%d%.]+","") instead to remove all non-numeric parts.
string.sub() works on the bytes of a string, not on its chars. There is a difference when the string contains Unicode text.
If the number is at the end of the string, extract it with
amount = tonumber(saveData.amounts[i]:match("%d+$"))
Lua strings are strings of bytes, not strings of characters. ASCII characters are 1 byte long, but most other characters consume multiple bytes, so using string.sub() isn't going to work.
There are several standards for converting between bytes and characters (or code points), but by far the most common on the web is UTF-8. If you are using Lua 5.3 or greater, you can use new built-in functions for performing UTF-8 manipulation. For example, to take a substring of a UTF-8 string, you can do:
-- Simple version without bounds-checking.
function utf8_sub1(s, start_char_idx, end_char_idx)
start_byte_idx = utf8.offset(s, start_char_idx)
end_byte_idx = utf8.offset(s, end_char_idx + 1) - 1
return string.sub(s, start_byte_idx, end_byte_idx)
end
-- More robust version with bounds-checking.
function utf8_sub2(s, start_char_idx, end_char_idx)
start_byte_idx = utf8.offset(s, start_char_idx)
end_byte_idx = utf8.offset(s, end_char_idx + 1)
if start_byte_idx == nil then
start_byte_idx = 1
end
if end_byte_idx == nil then
end_byte_idx = -1
else
end_byte_idx = end_byte_idx - 1
end
return string.sub(s, start_byte_idx, end_byte_idx)
end
s = "¥201"
print(string.sub(s, 2, 4)) -- an invalid byte sequence
print(utf8_sub1(s, 2, 4)) -- "201"
print(utf8_sub2(s, 2, 4)) -- "201"
print(utf8_sub1(s, 2, 5)) -- throws an error
If you don't have Lua 5.3, you can use a UTF-8 library like this one instead to achieve the same functionality.

Get the double part from string with vbscript

I want to create a barcode with vbscript that will be decoded from my company's erp (my company devides the nubers with 10000.
The barcode should have this type of look:
99XXXXXXXXXQQQQQQQQPPPPP where: X is my barcode, Q is quantity, and P is the price. With concatenation I have:
Result = 99 & [sheet$.BARCODE] & right("00000000" & quantity*10000, 8) & right("00000" & VBScript1*10000,5)
Now VBScript1 has this style, because it is used elsewhere in the program:
VBScript1 = "PRICE: "& FormatCurrency([sheet$.TIMH SAKOYLAKI]/[sheet$.SAKOYLAKI TWN]*1.3*(Round((40*CDbl(zyg))/CDbl([sheet$.GR/40 TEM]))),2)
so the output of VBScript1 is like Price: $0,40
Now my question is how to extract from the string the number only and then multiply it by 10000, in order to use it above?
For my example I want Price: Price: $0,40 to be used as 04000 in barcode.
Use Split() on $ to get the numerical part of (e.g.) "Price: $0,40", deal with the decimal comma, pad on the left:
>> s = "Price: $0,40"
>> p = CDbl(Replace(Split(s, "$")(1), ",", "."))
>> t = Right(String(5, "0") & p * 10000, 5)
>> WScript.Echo t
>>
04000
>>
Like Marc B said, I tried this and it worked nice and easy :)
Result =[...]right("00000" & CDbl((Mid(VBScript1,7,7)))*10000,5)[...]

Trimming strings in Scala

How do I trim the starting and ending character of a string in Scala
For inputs such as ",hello" or "hello,", I need the output as "hello".
Is there is any built-in method to do this in Scala?
Try
val str = " foo "
str.trim
and have a look at the documentation. If you need to get rid of the , character, too, you could try something like:
str.stripPrefix(",").stripSuffix(",").trim
Another way to clean up the front-end of the string would be
val ignoreable = ", \t\r\n"
str.dropWhile(c => ignorable.indexOf(c) >= 0)
which would also take care of strings like ",,, ,,hello"
And for good measure, here's a tiny function, which does it all in one sweep from left to right through the string:
def stripAll(s: String, bad: String): String = {
#scala.annotation.tailrec def start(n: Int): String =
if (n == s.length) ""
else if (bad.indexOf(s.charAt(n)) < 0) end(n, s.length)
else start(1 + n)
#scala.annotation.tailrec def end(a: Int, n: Int): String =
if (n <= a) s.substring(a, n)
else if (bad.indexOf(s.charAt(n - 1)) < 0) s.substring(a, n)
else end(a, n - 1)
start(0)
}
Use like
stripAll(stringToCleanUp, charactersToRemove)
e.g.,
stripAll(" , , , hello , ,,,, ", " ,") => "hello"
To trim the start and ending character in a string, use a mix of drop and dropRight:
scala> " hello,".drop(1).dropRight(1)
res4: String = hello
The drop call removes the first character, dropRight removes the last. Note that this isn't "smart" like trim is. If you don't have any extra character at the start of "hello,", you will trim it to "ello". If you need something more complicated, regex replacement is probably the answer.
If you want to trim only commas and might have more than one on either end, you could do this:
str.dropWhile(_ == ',').reverse.dropWhile(_ == ',').reverse
The use of reverse here is because there is no dropRightWhile.
If you're looking at a single possible comma, stripPrefix and stripSuffix are the way to go, as indicated by Dirk.
Given you only want to trim off invalid characters from the prefix and the suffix of a given string (not scan through the entire string), here's a tiny trimPrefixSuffixChars function to quickly perform the desired effect:
def trimPrefixSuffixChars(
string: String
, invalidCharsFunction: (Char) => Boolean = (c) => c == ' '
): String =
if (string.nonEmpty)
string
.dropWhile(char => invalidCharsFunction(char)) //trim prefix
.reverse
.dropWhile(char => invalidCharsFunction(char)) //trim suffix
.reverse
else
string
This function provides a default for the invalidCharsFunction defining only the space (" ") character as invalid. Here's what the conversion would look like for the following input strings:
trimPrefixSuffixChars(" Tx ") //returns "Tx"
trimPrefixSuffixChars(" . Tx . ") //returns ". Tx ."
trimPrefixSuffixChars(" T x ") //returns "T x"
trimPrefixSuffixChars(" . T x . ") //returns ". T x ."
If you have you would prefer to specify your own invalidCharsFunction function, then pass it in the call like so:
trimPrefixSuffixChars(",Tx. ", (c) => !c.isLetterOrDigit) //returns "Tx"
trimPrefixSuffixChars(" ! Tx # ", (c) => !c.isLetterOrDigit) //returns "Tx"
trimPrefixSuffixChars(",T x. ", (c) => !c.isLetterOrDigit) //returns "T x"
trimPrefixSuffixChars(" ! T x # ", (c) => !c.isLetterOrDigit) //returns "T x"
This attempts to simplify a number of the example solutions provided in other answers.
Someone requested a regex-version, which would be something like this:
val result = " , ,, hello, ,,".replaceAll("""[,\s]+(|.*[^,\s])[,\s]+""", "'$1'")
Result is: result: String = hello
The drawback with regexes (not just in this case, but always), is that it is quite hard to read for someone who is not already intimately familiar with the syntax. The code is nice and concise, though.
Another tailrec function:
def trim(s: String, char: Char): String = {
if (s.stripSuffix(char.toString).stripPrefix(char.toString) == s)
{
s
} else
{
trim(s.stripSuffix(char.toString).stripPrefix(char.toString), char)
}
}
scala> trim(",hello",',')
res12: String = hello
scala> trim(",hello,,,,",',')
res13: String = hello

Insert a character into a string at a specified index

So I have an array of indexes of characters in a string that I wish to insert a character before, how do i easily insert a character before each index? So for example:
"The big brown fox ... "
the positions
array = 4,9
the character to insert ','
the result: "The, big, brown fox ..."
Is there a method that provides such an easy utility?
String.insert(originalStr, index, stringToInsert) for example???
Update
The example I provided is just an example implementation. I also may want to do the following:
orginalText = "some text with characters like ; : } <"
in which I may want to insert "\" with the result being:
result = "some text with characters like \; : } \<"
This is hacky and a bit rushed but try this:
Dim sString: sString = "the something something"
Dim position: position = 1
Dim character: character = "F"
if position = 0 then
sString = character + Left(Mid(sString, 1), Len(sString) + 1)
else
sString = Left(sString, position) + character + Left(Mid(sString, position), Len(sString) - position + 1)
end if
Assuming that the indexes are sorted, loop backwards and insert each character.
For lngPos = UBound(alngPositions) to 0 step -1
strText = Left(strText, alngPositions(lngPos) - 1) + "," + Mid(strText, alngPositions(lngPos))
Next
Note that with your example data it will of course produce the string "The, big ,brown fox ... ". The indexes are not pre-added to match the position in the resulting string, are they?
Edit:
An alternative that would be faster for large strings, is to split up the string at the index positions into an array, then join the strings with commas in between:
Dim astrSubstrings(UBound(alngPositions) + 1)
lngLeft = 1
For lngPos = 0 to UBound(alngPositions)
astrSubstrings(lngPos) = Mid(strText, lngLeft, alngPositions(lngPos) - lngLeft)
lngLeft = alngPositions(lngPos)
Next
astrSubstrings(UBound(alngPositions) + 1) = Mid(strText, lngLeft)
strText = Join(astrSubstrings, ",")
I'm not a classic ASP user but you can use substring to get the part of the string up to the index where you have to insert the character, substring the other part of the string and take these two parts and build a new string doing part1 & "," & part2.
Hope it helps.
You should be able to use the split function based on the space between the words - this will return an array of words. You then put a comma after each item in the array and you can get to the requried string that you are looking for. Example here http://www.w3schools.com/VBscript/func_split.asp
It's been a while, but Mid(str, start, [end]) would be the way to go.

Resources