Hvordan kan jeg finde en given tekst i en streng? Derefter vil jeg gerne oprette en ny streng mellem den og noget andet. For eksempel...
Hvis strengen var:
This is an example string and my data is here
Og jeg ønsker at oprette en streng med det, der er mellem "min " og " er" hvordan kan jeg gøre det? Undskyld dette er temmelig pseudo, men forhåbentlig giver det mening.
Brug denne funktion.
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
Sådan bruger du den:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
string string1 = "This is an example string and my data is here";
string toFind1 = "my";
string toFind2 = "is";
int start = string1.IndexOf(toFind1) + toFind1.Length;
int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
string string2 = string1.Substring(start, end - start);
Hvis du ved, at du altid vil have strengen mellem "my" og "is", kan du altid udføre følgende:
string message = "This is an example string and my data is here";
//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;
//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);
//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();