0

I want to insert a word inside an existing word? Both are Strings.

For example:

Given String word:

HELLO SAMPLE SENTENCE

i want to insert the word I AM A so my output would be:

HELLO I AM A SAMPLE SENTENCE

i am inserting here basing on the word SAMPLE. So the insertion starts before the word SAMPLE. is this possible?

2
  • 1
    What logical are you criteria are you using to make this decision? Commented Aug 26, 2013 at 4:36
  • is this possible with RegEx? i am not good with RegEx but i think it has to do with it. Commented Aug 26, 2013 at 4:42

3 Answers 3

3

Based on the description of your logic (which isn't much to go on), I would use:

Dim input As String = "HELLO SAMPLE SENTENCE"
Dim iSample As Integer = input.IndexOf("SAMPLE")
Dim output As String = input.Insert(iSample, "I AM A ")

This uses the BCL function String.Insert, which simply inserts a string into another string at a particular position.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice. Don't hardcode a 6, but use input.IndexOf("SAMPLE") instead
Thanks alot this worked. This will be added to my notes. I am still learning the basics.
@Jacob, good point, I looked around for something relating to the logic of where he wanted to insert, missed that somehow. Edited.
1

Create a function like this:

Function InsertBefore(sentence As String, find As String, textToInsert As String
    Return sentence.Replace(find, textToInsert+Find)
End Function

And call it like this:

sentence = InsertBefore("HELLO SAMPLE SENTENCE", " SAMPLE ", "I AM A")

Comments

-1

If I remember correctly, you can use the String.split() function on your string.

See DotNetPerls' page on Split here.

You can split the string into an array, then insert the line you want into the array, then join them back together using String.Join() (thanks Monty, I don't use Visual Basic that frequently anymore, I forgot that :)).

Hope this help :)

1 Comment

You can also join using a String.Join() (msdn.microsoft.com/en-us/library/system.string.join.aspx)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.