Πώς μπορώ να βρω δεδομένο κείμενο μέσα σε μια συμβολοσειρά; Μετά από αυτό, θα ήθελα να δημιουργήσω ένα νέο αλφαριθμητικό μεταξύ αυτού και κάτι άλλου. Για παράδειγμα...
Αν η συμβολοσειρά ήταν:
This is an example string and my data is here
Και θέλω να δημιουργήσω μια συμβολοσειρά με οτιδήποτε βρίσκεται μεταξύ των "my " και " is" πώς θα μπορούσα να το κάνω αυτό; Συγγνώμη αυτό είναι αρκετά ψευδο, αλλά ελπίζω να βγάζει νόημα.
Χρησιμοποιήστε αυτή τη λειτουργία.
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 "";
}
}
Πώς να τη χρησιμοποιήσετε:
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);
Αν γνωρίζετε ότι θέλετε πάντα τη συμβολοσειρά μεταξύ των "my" και "is", τότε μπορείτε πάντα να εκτελέσετε τα εξής:
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();