这是我的动态字符串:
String a= "SourceFilePath:C:\Users\Anuj\Desktop\Anuj Tamrakar Working Folder, BackUpFilePath:C:\Users\Anuj\Desktop\installer, SyncPath:C:\Users\Anuj\Desktop\PSI, Password:3SMpUGoJpIJdWwRDXau+OQ==, NumberOfTimes:2, Time0:10:10 AM, Time1:10:10 PM"
我需要读取字符串的内容,并且需要将每个键及其coressponding值存储到变量中。我需要像
这样的输出var SourceFilePath = "C:\Users\Anuj\Desktop\Anuj Tamrakar Working Folder";
var BackUpFilePath="C:\Users\Anuj\Desktop\installer"
var SyncPath="C:\Users\Anuj\Desktop\PSI"
var Password="3SMpUGoJpIJdWwRDXau+OQ=="
var NumberOfTimes=2
var Time0=10:10 AM
var Time1=10:10 PM
这部分是动态的:
var NumberOfTimes:2
var Time0:10:10 AM
var Time1:10:10 PM
如果我的字符串文件中有NumberOfTimes:4
。我会有4个时间值,即Time0,Time1,Time2和Time3。所以我需要将这4个时间值存储到4个变量中
答案 0 :(得分:0)
您可以使用字典对象。
拆分字符串输入,然后循环遍历变量键值对:。 将密钥和值存储在字典中。
您不需要声明每个变量,但您可以通过键在字典中查找。
答案 1 :(得分:0)
必须是下面的内容。
// you can also fill an array dynamically
var NumberOfTimes=["10:10 AM","10:11 AM","10:12 AM"]
//count of stored items in array
NumberOfTimes.length
//in order to print or use in some where else
NumberOfTimes.forEach(function(e,i){
//do somethings
});
答案 2 :(得分:0)
我在控制台应用中尝试了这个并且工作正常。以下是我的解决方案。
static void Main(string[] args)
{
String a = @"SourceFilePath:C:\Users\Anuj\Desktop\Anuj Tamrakar Working Folder, BackUpFilePath:C:\Users\Anuj\Desktop\installer, SyncPath:C:\Users\Anuj\Desktop\PSI, Password:3SMpUGoJpIJdWwRDXau+OQ==, NumberOfTimes:2, Time0:10:10 AM, Time1:10:10 PM";
Dictionary<string, string> processedString = ProcessString(a);
//Here you can set the values to variable accessing it from the Dictionary
var SourceFilePath = processedString["SourceFilePath"];
var BackUpFilePath = processedString["BackUpFilePath"];
var SyncPath = processedString["SyncPath"];
var Password = processedString["Password"];
var NumberOfTimes = Convert.ToInt32(processedString["NumberOfTimes"]);
// And for the dynamic variables like Time01, Time02 I recommend you to create a list which holds all the time components.
// Because creating a variable on the fly will be more complex for your requirement and is not necessary at this moment.
//So you can do this
var TimeComponents = processedString.Where(x => x.Key.StartsWith("Time")).Select(x => x).ToList();
Console.ReadLine();
}
分割字符串和创建字典的过程如下所示。
public static Dictionary<string, string> ProcessString(string toProcess)
{
Dictionary<string, string> processedString = new Dictionary<string, string>();
var eachSubString = toProcess.Split(',');
foreach (var subStr in eachSubString)
{
var keyValue = subStr.Trim().Split(new char[] { ':' }, 2);
processedString.Add(keyValue[0], keyValue[1]);
}
return processedString;
}
这是调试器的屏幕截图
如果有帮助,请告诉我。