简体   繁体   English

比较C#中的两个字符串

[英]Comparing two strings in c#

My problem is like,I am trying to compare two strings,one is present inside the file (let say CS M 22+ ) and the other one is in the file name (let say csm22+westbengal@v2 ). 我的问题是,我正在尝试比较两个字符串,一个在文件内(让我们说CS M 22+ ),另一个在文件名中(让我们说csm22+westbengal@v2 )。 I have to check whether the string present inside the file name ie CS M 22+ matches to the string present in the filename ie csm22+westbengal@v2 . 我必须检查文件名(即CS M 22+中存在的字符串是否与文件名(即csm22+westbengal@v2存在的字符串匹配。

String inside the file CS M 22+ is called the target name and string present in the file name is suffix with the market name ie csm22+ then the market name westbengal@v2. 文件CS M 22+中的字符串称为目标名称,文件名中存在的字符串后缀为市场名称csm22 +,然后为市场名称westbengal @ v2。

Below is the logic I have implemented where I am comparing char of both the strings. 下面是我在比较两个字符串的char时实现的逻辑。 But that logic fails if while testing, I have changed my inside the file string to CS M 22 ie if I remove any thing from the inside file string (CS M 22+) , this logic fails. 但是,如果在测试时,我已将内部文件字符串更改为CS M 22 ,则该逻辑失败,即,如果从内部文件字符串(CS M 22+)中删除了任何内容,则此逻辑将失败。

If both are match then it is fine else I am writing the file name. 如果两者都匹配,那很好,否则我正在写文件名。

//For your reference 
//splittedTGMKTName  = csm22+westbengal@v2
//trimedTGMKTName    = csm22+
// and the below logic fails if i remove anything from the trimedTGMKTName like if
// i remove "+" and the logic works fine if i added anything to the trimedTGMKTName and then compare

foreach (var chr in splittedTGMKTName.ToCharArray())
{
    if (isContentLoopComplete)
    {
        if (lastChar == '-' || lastChar == '+' || chr == '-' || chr == '+')
        {
            isOldFile = true;
            break;
        }
    }

    for (int i = jpointer; i < trimedTGMKTName.ToCharArray().Length; )
    {
        if (trimedTGMKTName.Length - 1 == i)
        {
            isContentLoopComplete = true;
            lastChar = chr;
        }

        if (chr != trimedTGMKTName[i])
        {
            isbreak = true;
        }

        jpointer++;
        break;
    }

    if (isbreak)
        break;
}

if (!isOldFile)
{
    fileCount = ++fileCount;
    hasErrors = true;
    sw = new StreamWriter(folderPath + "/" + "Files_with_mismatch_TGMKT_Names_" + folder.Name + ".txt", true);
    sw.WriteLine(fileName);
    sw.Close();
}

Any help would be appreciated.Thanks. 任何帮助将不胜感激。

You can use the StartsWith function if you want to check if your function is at the beginning of calling one: Example: 如果要检查函数是否在调用一个函数的开头,可以使用StartsWith函数:示例:

string src="csm22+westbengal@v2";
src.StartsWith("csm22")// will return true

if you wanna check if the string contains another you can use the Contains function. 如果要检查字符串是否包含另一个字符串,可以使用Contains函数。 for Equality you can use Equals . 为了平等,您可以使用Equals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM