- This topic has 3 replies, 2 voices, and was last updated 9 years, 1 month ago by .
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- You must be logged in to reply to this topic.
Integrated Application Platform
Integrated Application Platform › Forums › General › [SOLVED]A string composing function to share
I find it difficult to read and compose complex strings with $,”, space and substrings. So I came up with the another function to simplify the process.
StringFormat
function (@args)
{
str = args[0]
subStrings = Object()
for(i=1;i<=args.Size()-1;++i)
{
subStrings.Add(args)
}
j = 0
for (s in subStrings)
{
++j
if (str.Find('%' $ String(j)) is str.Size())
throw ('String format is invalid')
str = str.Replace('%' $ String(j), s, 1)
}
return str
}
How to use it:
str = StringFormat('yes, %1 %2 %3!', 'I', 'love', 'banana')
Print(str)
Result:
yes, I love banana!
The %n is an unlimited series of integer numbers starting from %1. The sub strings you can put in are also unlimited and can be any data type.
Maybe the error handling can be improved a little but you can hardly miss it.
Hope you find it useful.
Here’s an approach that uses the block form of Replace:
args = #("%2 %1 %3", one, two, three)
args[0].Replace("%[0-9]+", { args[Number(it[1..])] })
This might also be a candidate for adding as a method in Strings so you could say: string.Format(args)
Wow! that’s really short and sweet. Thanks Andrew.
Just one little suggestion, it would be nice to just supply the parameters as comma separated instead of an object, as it will save time for typing and reading later on when it is used.
Cheers
When you use @args the arguments are put in an object for you, so you can call it with just regular arguments.
function (@args)
{
return args[0].Replace(“%[0-9]+”, { args[Number(it[1..])] })
}