views:

1163

answers:

5

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 \; \: } \<"

A: 

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.

Sebastian
A: 

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

OpenSource
my intention is not to place commas before spaces but to insert a character at a given position in a string. this was merely an example.
predhme
ok got it... mid is the way to go then.
OpenSource
A: 

It's been a while, but Mid(str, start, [end]) would be the way to go.

mattl
+2  A: 

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
Jon
with a very minor tweak that did the job! thanks a ton
predhme
+1  A: 

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, ",")
Guffa