1

It might be very simple but would like to know that,is there any alternative to find a string between a source string which by passing it start and end string

the following is achievable by this code ,but this there any better code than this as i think this will slow the system if used in many conditions.

    string strSource = "The LoadUserProfile call failed with the following error: ";
    string strResult = string.Empty;
    string strStart = "loaduserProfile";
    string strEnd = "error";

    int startindex = strSource.IndexOf(strStart, StringComparison.OrdinalIgnoreCase);
    int endindex = strSource.LastIndexOf(strEnd, StringComparison.OrdinalIgnoreCase);

    startindex = startindex + strStart.Length;

    int endindex = endindex - startindex;
    strResult = strSource.Substring(startindex, endindex);

Thanks D.Mahesh

2 Answers 2

1

Use regex and find the group value, but not sure if it will be faster or slower.

Here is an example code to implement this using Regex (no VS, so excuse if there is syntax error)

string pattern = Regex.Escape(strStart) + "(?<middle>[\s\S]*)" + Regex.Escape(strEnd); 
Match match = Regex.Match(strSource, pattern);
if (match.Success)
{
   // read the group value matches the name "middle"
   ......
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your code is pretty spot-on string manipulation. I don't think it can be made faster algorithmically. You can also do this using a regular expression, but I don't believe it will end up being faster in that case as well.

If you don't need case insensitivity, changing StringComparison.OrdinalIgnoreCase to StringComparison.Ordinal should provide some speedup.

Otherwise, you probably have to look elsewhere for speed improvements.

2 Comments

A RegEx approach will probably produce fewer lines of C# code though. OP should perhaps investigate if the desired string (information) can be obtained directly from a different - and structured - source.
There may be fewer lines of code with a regex, but it wouldn't be faster, and it's questionable whether it would be easier to understand.

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.