gpt4 book ai didi

c# - 识别那些不同的字符

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:46 24 4
gpt4 key购买 nike

我应该编写一个程序来识别字符串对之间的差异,以便人类更容易看出差异。

程序应该以视觉上引人注目的方式识别两个给定字符串之间不同的字符。

将两个输入字符串分两行输出,然后在下一行使用句点(相同字符)和星号(不同字符)标识不同之处。

例如:

ATCCGCTTAGAGGGATT
GTCCGTTTAGAAGGTTT
*....*.....*..*..

第一行输入包含一个整数1≤n≤500,表示后面的测试用例个数。每个测试用例都是一对等长的行,1 到 50 个字符。每个字符串仅包含字母(a-z、A-Z)或数字(0-9)。

但是我不能把匹配的字符改成指针?我能得到一些帮助吗?而且我真的不明白如何表示测试用例的数量?

using System;
using System.Linq;

public class Program
{
public static void Main()
{
string s1 = "abcdefg";
string s2 = "acceeff";

string s3 = "hbcdfgi";
string s4 = "hbadehi";

char[] c1 = s1.ToCharArray();
char[] c2 = s2.ToCharArray();
char[] c3 = s3.ToCharArray();
char[] c4 = s4.ToCharArray();

var diff = s1.Except(s2);
string newS1 = s1;
foreach(var value in diff)
{
newS1 = newS1.Replace(value, '*');

}
var diff2 = s3.Except(s4);
string newS2 = s3;
foreach(var value in diff2)
{

newS2 = newS2.Replace(value, '*');

}
string nr1 = s1 + "\n" + s2;
string nr2 = s3 + "\n" + s4;

Console.WriteLine(nr1);
Console.WriteLine(newS1);
Console.WriteLine();
Console.WriteLine(nr2);
Console.WriteLine(newS2);
Console.WriteLine();
}

}

最佳答案

我不知道你是如何存储你的测试用例以便能够对此发表评论的,但基本上对于每个测试用例你只需要输出 2 个值,然后循环其中一个来检查匹配并输出根据匹配正确的字符。

所以对于每个测试用例(字符串对),你只想做这样的事情:

string s1 = "abcdefg";
string s2 = "acceeff";

// Write each input string to console.
Console.WriteLine(s1);
Console.WriteLine(s2);

// Loop each character and check for match.
for(int i = 0; i < s1.Length; i++)
{
if(s1[i] == s2[i]) // If match output "."
Console.Write(".");
else // otherwise, output "*"
Console.Write("*");
}

// Write a new line ready for the next test case.
Console.WriteLine();

关于循环测试用例,您基本上需要一个包含字符串的客户类的 List。例如:

class TestCase
{
public string S1 { get; set; }
public string S2 { get; set; }
}

然后您需要以某种方式创建一个列表(可能从文件或硬代码中读取):

List<TestCase> testCases = new List<TestCase>
{
new TestCase { S1 = "abcdef", S2 = "abcxyz" },
new TestCase { S1 = "abc", S2 = "def" }
};

然后你像这样循环:

foreach(var testCase in testCases)
{
string s1 = testCase.S1;
string s2 = testCase.S2;

// Rest of code from above.
}

关于c# - 识别那些不同的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48446610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com