1

How to replace string between some Specific String in c# For Exmaple

string temp = "I love ***apple***";

I need to get value between "***" string, i.e. "apple";

I have tried with IndexOf, but only get first index of selected value.

1
  • 1
    IndexOf has an overload that also gets the index at which to start searching. If you give it the previously found index + 1, you will find the next occurrence of the given string. Note that people are going to answer you very soon with some Regex, and to that I tell you - don't. Commented Mar 19, 2016 at 10:29

1 Answer 1

2

You should use regex for proper operation of various values like ***banana*** or ***nut*** so the code below may useful for your need. I created for both replacement and extraction of values between *** ***

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace RegexReplaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string temp = "I love ***apple***, and also I love ***banana***.";
            //This is for replacing the values with specific value.
            string result = Regex.Replace(temp, @"\*\*\*[a-z]*\*\*\*", "Replacement", RegexOptions.IgnoreCase);
            Console.WriteLine("Replacement output:");
            Console.WriteLine(result);

            //This is for extracting the values
            Regex matchValues = new Regex(@"\*\*\*([a-z]*)\*\*\*", RegexOptions.IgnoreCase);
            MatchCollection matches = matchValues.Matches(temp);
            List<string> matchResult = new List<string>();
            foreach (Match match in matches)
            {
                matchResult.Add(match.Value);
            }

            Console.WriteLine("Values with *s:");
            Console.WriteLine(string.Join(",", matchResult));

            Console.WriteLine("Values without *s:");
            Console.WriteLine(string.Join(",", matchResult.Select(x => x.Trim('*'))));
        }
    }
}

And a working example is here: http://ideone.com/FpKaMA

Hope this examples helps you with your issue.

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.