如何使用子字符串以及如何将一个变量分解为两个变量

本文关键字:变量 分解 何使用 两个 一个 字符串 | 更新日期: 2023-09-27 18:27:38

使用子字符串时,我一直在努力解决问题。

C#:

string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";

我想要什么:

  • 使用子字符串删除"{"、"receive:"answers"}"
  • 然后将sInput分解为新的两个变量,例如:

来自:

string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";

到:

string sMeal = "vegetable lasgane";
string sReceipt= "cheese sauce etc...";

如何在C#中做到这一点?您的代码示例将非常适用。谢谢

如何使用子字符串以及如何将一个变量分解为两个变量

string sInput = "vegetable lasgane { receipt: cheese sauce etc...}";
string[] splitString = sInput.Split('{');
string firstString = splitString[0];
string secondString = splitString[1].Replace("}", "").Split(':')[1];

也许应该会成功。

只需像这样使用String.SubStringString.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...

这里是演示

试用value.split("{");

更多示例如下:http://www.dotnetperls.com/split

这并不难:

sMeal = sInput.Split(" { receipt: ")[0];

sReceipt = sInput.Split(" { receipt: ")[1];
sReceipt = sReceipt.Substring(0,sReceipt.Length-1);

输出:餐点:蔬菜烤宽面条收据:奶酪酱等。

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;
            }
        }

}

您可以使用Replace()来删除字符,使用Split("{")来分离两个字符串

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];
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