在 C# 中匹配 2 个字符串 [英] Matching 2 strings in C#

查看:64
本文介绍了在 C# 中匹配 2 个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个字符串.这 2 个字符串的大小可能不同.我想看看这 2 个字符串找到匹配的序列.一旦我找到一个变化,我想在大写中打印那个词,然后在我的字符串中继续,直到我找到另一个变化,依此类推.我不知道我会怎么做,我试着从整体上看单词,但我遇到了问题.基本上我将有 2 个类似这样的字符串 string one="This is a new value"string two="This 这是一个新的品牌价值".我想从一开始就遍历每个字符串并找到匹配的序列,例如这是"在字符串处停止,意识到添加字符串时它已更改,将其更改为大写,然后继续.预期输出 =这是一个新的 ALSO BRAND 值"

I have 2 strings. These 2 strings can differ in size. I want to look at these 2 strings finding matching sequences. Once I find a change I want to print that word in Capital and then continue on in my string until I find another change and so on. I'm not sure how I would go about this I tried looking at words as a whole but I'm having issues with that. Basically I will have 2 string something like this string one="This is a new value" and string two= "This This is a new also brand value". I want go though each string from the start and find the matching sequences e.g. "This is" stop at string realise it has changed as string was added change it to upper case and then carry on. Expected output ="THIS this is a new ALSO BRAND value "

我正在尝试一些代码.我认为这不是正确的方法.

Some code I was trying. I don't think this is the right approach.

 static void Main(string[] args)
        {
            string one = "This is a new value";
            string two = "This This is a new also brand value";

            var coll = two.Split(' ').Select(p => one.Contains(p) ? p : p.ToUpperInvariant());

            Console.WriteLine(string.Join(" ", coll));
            Console.ReadKey();
        }

推荐答案

这是您要找的吗?描述不是很好,但从答案来看,这似乎是在同一个范围内,并且它使用 LINQ 以减少代码和复杂性.

Is this what you're looking for? The description isn't fantastic, but judging by the answers this seems to be in the same ballpark, and it uses LINQ for less code and complication.

class Program
{
    static void Main(string[] args)
    {
        string one = "This is text one";
        string two = "This is string text two not string one";

        var coll = two.Split(' ').Select(p => one.Contains(p) ? p : p.ToUpperInvariant());

        Console.WriteLine(string.Join(" ", coll)); // This is STRING text TWO NOT STRING one
        Console.ReadKey();
    }
}

您可以将其分解为一个单独的方法,并将您的变量作为参数传入.

You can break this out to a separate method and pass your variables in as parameters.

这篇关于在 C# 中匹配 2 个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆