当我使用substring时,我一直在努力解决我的问题。
C#:
string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";
我想要的:
来自:
string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";
以
string sMeal = "vegetable lasgane";
string sReceipt= "cheese sauce etc...";
如何在C#中执行此操作?您的代码示例将非常适用。谢谢!
答案 0 :(得分:2)
string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";
string[] splitString = sInput.Split('{');
string firstString = splitString[0];
string secondString = splitString[1].Replace("}", "").Split(':')[1];
应该可以做到这一点。
答案 1 :(得分:1)
只需使用String.SubString
和String.IndexOf
这样的方法;
string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";
string sMeal = sInput.Substring(0, sInput.IndexOf('{'));
Console.WriteLine(sMeal);
//vegetable lasgane
string sReceipt = sInput.Replace('{', ' ').Replace('}', ' ');
sReceipt = sReceipt.Substring(sReceipt.IndexOf(':') + 1).Trim();
Console.WriteLine(sReceipt);
//cheese sauce etc...
这是DEMO。
答案 2 :(得分:0)
你可以Replace()
删除字符,Split("{")
分隔2个字符串
string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";
sInput = sInput.Replace("}", "");
sInput = sInput.Replace("receipt:", "");
string[] Parts = sInput.Split('{');
现在可能Trim()
如果需要
string sMeal = Parts[0].Trim();
string sReceipt= Parts[1];
答案 3 :(得分:0)
尝试使用value.split("{");
此处有更多示例:http://www.dotnetperls.com/split
答案 4 :(得分:0)
这不是很难:
sMeal = sInput.Split(" { receipt: ")[0];
和
sReceipt = sInput.Split(" { receipt: ")[1];
sReceipt = sReceipt.Substring(0,sReceipt.Length-1);
答案 5 :(得分:0)
产量:膳食:蔬菜烤宽面条食谱:奶酪酱等......
public void Foo()
{
int updationIndex = 0;
Func<string, char, string> getMyString1 = (givenString, takeTill) =>
{
var opString =
new string(
givenString.ToCharArray()
.TakeWhile(x => x != takeTill)
.ToArray());
updationIndex = inputString.IndexOf(givenString, StringComparison.CurrentCultureIgnoreCase)
+ opString.Length;
return opString;
};
var smeal = getMyString1(inputString, '{');
Console.WriteLine("Meal: " + smeal);
while (updationIndex < inputString.Length)
{
var sReceipt = getMyString(inputString.Remove(0, updationIndex), ':', '}');
Console.WriteLine("sReceipt: "+ sReceipt);
if (string.IsNullOrWhiteSpace(sReceipt))
{
break;
}
}
}
答案 6 :(得分:0)
string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";
string one = sInput.Substring(0, sInput.IndexOf("{"));
int start = sInput.IndexOf("{");
int end = sInput.IndexOf("}");
string two = sInput.Substring(start + 1, end - start - 1);
Response.Write(one + "\n"); // your 1st requirement
Response.Write(two + "\n"); // your 2nd requirement