Reputation: 39
I have some string and I would like to order the content.
string nr1 = "Number: 5 Specialty: Technology Role: Teacher";
string nr2 = "Specialty: Informatics Number: 1 Role: Student";
string nr3 = "Role: Teacher Specialty: Geography Number:10"
I would like to keep the following format: "Role: X Number: Y Speciality: Z"; Is there a way to do this?
Upvotes: 1
Views: 117
Reputation: 628
There are various approach to achieve it, I have done it by converting the string into list of strings. I hope this may help you out.
string nr1 = "Number: 5 Specialty: Technology Role: Teacher";
List<string> stringAsList = nr1.Split(' ').ToList();
StringBuilder reorderedString = new StringBuilder();
int indexRole = stringAsList.FindIndex(x => x.Contains("Role:"));
int indexNumber = stringAsList.FindIndex(x => x.Contains("Number:"));
int indexSpeciality = stringAsList.FindIndex(x => x.Contains("Specialty:"));
reorderedString.Append($"Role: {stringAsList[indexRole + 1]} Number: {stringAsList[indexNumber + 1]} Speciality: {stringAsList[indexSpeciality + 1]}");
Upvotes: 3
Reputation: 45947
RegEx approach by parsing out the required values
using System.Text.RegularExpressions;
string nr1 = "Number: 5 Specialty: Technology Role: Teacher";
var n1 = Regex.Match(nr1, "(?<=Number: )\\w+");
var s1 = Regex.Match(nr1, "(?<=Specialty: )\\w+");
var r1 = Regex.Match(nr1, "(?<=Role: )\\w+");
string result = string.Format("Role: {0} Number: {1} Speciality: {2}", r1, n1, s1);
https://dotnetfiddle.net/Nu9MDg
Upvotes: 4