简体   繁体   中英

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 ). 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 .

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.

Below is the logic I have implemented where I am comparing char of both the strings. 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.

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:

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. for Equality you can use Equals .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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