我需要在c#中使用For循环比较2个字符串

Mth*_*b54 2 c# string compare

我需要使用For比较2个字符串而不使用String.compare.(这是一个家庭作业......我开始编程C#2周前)

我只是无法弄清楚如何使用for循环来回答这个问题.我不知道要放什么().我尝试了for( string text1 = "something",)但是我无法弄清楚在for循环之后输出了什么.

vcs*_*nes 5

由于这是一个家庭作业问题,我建议您在最终获得解决方案之前,一旦认为自己有足够的信息自行解决问题,请立即停止阅读答案.

让我们假设一个简单的方法签名,首先:

public static bool AreStringEqual(string str1, string str2)
{
}
Run Code Online (Sandbox Code Playgroud)

我们的目标是实现(编写代码)此方法.我们假设我们的目标是如果字符串相等返回true,如果不相等则返回false.我们不会做任何花哨的事情,比如说它不区分大小写.

我们首先可以对字符串进行一些基本检查.如果它们的长度不同,那么我们可以立即假设字符串不同,并返回false:

if (str1.Length != str2.Length)
{
    return false;
}
Run Code Online (Sandbox Code Playgroud)

此块检查长度,如果它们不同,则立即返回false,并且不执行该方法的其余部分.

此时我们可以保证字符串的长度相同,因此我们可以循环遍历字符串并使用for循环逐个字符地比较它们.

for(int counter = 0; counter < str1.Length; counter++)
{
}
Run Code Online (Sandbox Code Playgroud)

这是一个非常标准的for-loop,它只计算一个从0到1的数字,而不是字符串的长度.因为我们已经知道它们是相同的长度,所以我们使用str1str2用于循环的上限并不重要.

要获取字符串中的字符,我们可以使用Indexer Syntax将字符放在给定位置.C#和.NET中的数字从零开始.

str1[0]获得第一个角色,str1[1]获得第二个角色,等等.

然后,我们可以插在for循环变量入索引的str1str2,然后比较字符.如果它们不相等,则返回false.

for(int counter = 0; counter < str1.Length; counter++)
{
    if (str1[counter] != str2[counter])
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,如果代码通过for循环而不返回false,则在结尾处返回true.把它们放在一起,它看起来像这样:

public static bool AreStringEqual(string str1, string str2)
{
    if (str1.Length != str2.Length)
    {
        return false;
    }
    for(int counter = 0; counter < str1.Length; counter++)
    {
        if (str1[counter] != str2[counter])
        {
            return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)