0

What i'm trying to do is insert a string <a href=\"{href}\">{text}</a> in a larger wall of article text but the large wall of text looks like:

{word|word|word} {word|word|word} {word|word|word} {word|word|word|word} etc

I'm looking to insert <a href=\"{href}\">{text}</a>"; randomly, but it has to be between one of these } { curly brackets so it will look like } <a href=\"{href}\">{text}</a> {

The way my code is now it just inserts anywhere (i know i need to add the logic to look between the brackets) which is where my issue is, i'm not sure the best way to do this.

Code:

        public static string GetAndInjectAhrefLinkIntoArticle(string article, string href, string text) {
            string injectedArticle = null;
            try {
                var rnd = new Random();
                string stringToInsert = $"<a href=\"{href}\">{text}</a>";

                int length = article.Length;
                if (length > 0)
                {
                    int pos = rnd.Next(0, length);
                    injectedArticle = article.Insert(pos, stringToInsert);
                }
            }
            catch (Exception ex)
            {
                DebugLogging($"[{DateTime.Now}]-[{ex}]");
            }
            return injectedArticle;
        }

Any help would be appreciated.

1
  • 1
    Collect the indexes of the "} {" substrings, select one of them randomly, then insert the link there. Commented Mar 6, 2021 at 8:44

1 Answer 1

2

I suggest you use pos = article.IndexOf("} {", pos) + 1 after you pick a random pos, to find the location of the next } {, and when you insert, insert an extra space at the start of stringToInsert..

If IndexOf returns -1, you might have tried too near the end; you could either:

  • Accept it will insert at the start (-1 becomes 0 when +1'd so it's valid)
  • Go again with another random (i.e. use a while(pos == 0) ..., or
  • Look at using LastIndexOf to give a more suitable upper bound for your random so it will always find the last } {
Sign up to request clarification or add additional context in comments.

Comments

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.