我有一些字符串,我想订购内容。
string nr1 = "Number: 5 Specialty: Technology Role: Teacher";
string nr2 = "Specialty: Informatics Number: 1 Role: Student";
string nr3 = "Role: Teacher Specialty: Geography Number:10"
我想保留以下格式:“角色:X数字:Y专长:Z”; 有办法吗?
答案 0 :(得分:4)
RegEx方法通过解析所需的值
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);
答案 1 :(得分:2)
有多种方法可以实现它,我通过将字符串转换为字符串列表来实现。我希望这可以帮助您。
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]}");