0

我需要测试一个字符串以查看它是否以任何字符串数组结尾。

我按照这个答案找到了使用 LINQ 的完美解决方案:

string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));

现在我想得到匹配的字符串,这就是我目前遇到的问题。


我尝试在最后添加

text_field.Text = x;

并且错误地显示了有关范围的消息 - 理所当然地,我期待这个错误。我还尝试声明一个x在最顶部命名的字符串变量,但又出现了另一个错误 - 关于无法在不同范围内重新声明变量的问题。我想我已经习惯了 PHP,你可以毫无问题地重新声明一个变量。

4

3 回答 3

2

我会为此使用正则表达式

string test = "foo+";
var match = Regex.Match(test, @".+([\+\-\*\\])$").Groups[1].Value;

""如果字符串+-*/

于 2018-05-01T19:49:50.973 回答
0

你最好的选择是做一个FirstOrDefault然后检查它是否为空/空/等,就好像它是你的布尔值一样。尽管这是一个非常基本的示例,但它应该能够理解这一点。您对该结果的处理方式以及是否应该只是一个或多个等取决于您的情况。

    static void Main()
    {
        string test = "foo+";
        string[] operators = { "+", "-", "*", "/" };
        bool result = operators.Any(x => test.EndsWith(x));

        string actualResult = operators.FirstOrDefault(x => test.EndsWith(x));

        if (result)
        {
            Console.WriteLine("Yay!");
        }

        if (!string.IsNullOrWhiteSpace(actualResult))
        {
            Console.WriteLine("Also Yay!");
        }
    }
于 2018-05-01T19:50:13.080 回答
0

如果我理解正确,这将为您提供操作员

string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
var result = operators.Where(x => test.EndsWith(x)) ;

这只会返回最后使用的运算符,因此如果它以 -+* 结尾,它将为您提供字符串中的最后一个字符

于 2018-05-01T19:52:32.530 回答