1

I need extract part of a text string (in this case everything after "Data Source =" .

"Data Source=xxxxx"

In VBA, there is a function call Mid()

strText = "Data Source=xxxxx"
var = Mid(strText, 12)

Is there anything similar in C#?

1

3 Answers 3

2

You can use String.Substring(Int32) overload;

Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

string strText = "Data Source=xxxxx";
string s = strText.Substring(12);

s will be xxxxx

Here a demonstration.

On your case using IndexOf method or Split method would be better IMO..

string s = strText.Substring(strText.IndexOf('=') + 1);

or

string s = strText.Split(new []{'='}, StringSplitOptions.RemoveEmptyEntries)[1];
Sign up to request clarification or add additional context in comments.

Comments

2

You want a substring starting from 12, and outwards:

var source = strText.Substring(12);

Alternatively, you could start from the index after the = (in case you want similar stuff from other settings):

var foundValue = strText.Substring(strText.IndexOf("=") + 1);

1 Comment

+1 for IndexOf. It makes it clear what it is doing. If you use var source = strText.Substring(12), at least comment it so other people know that it takes a string in the format Data Source=xxxxx and gives you xxxxx
1

Try this

string originalText = "Data Source = whatever is your text here";
string consText = "Data Source =";

string result = originalText.Substring(originalText.IndexOf(consText) + consText.Length);

This will be the simplest and significant way to achieve what you want as you just need to set the constantText you want and get everything after this text.

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.