谁能帮助我理解此C ++代码?

时间:2020-07-09 06:55:32

标签: c++ for-loop while-loop

我向您解释了该程序的工作。

步骤1:输入编号。您想运行循环的时间。

步骤2:输入两个字符串s1和s2。

输出:它将为您提供一个字符串s3,其中不包含字符串s2中的任何字符。

问题:我无法理解for循环的工作原理,哈希值为何为257以及循环如何工作。

下面给出了代码。

#include <iostream>
using namespace std;
#include<string.h>
int main()
{
    int t;
    cout<<"enter any no. to run the loop"<<endl;
    cin>>t;
    while(t--)
    {
        string s1,s2,s3;
        int i,j,l1,l2;
    cout<<"enter two strings s1 and s2"<<endl;
        cin>>s1>>s2;
        l1=s1.length( );
         l2=s2.length( );
         int hash[257];
         for(i=0;i<257;i++)
         {
             hash[i]=0;
         }
          for(i=0;i<l2;i++)
         {
             hash[s2[i]]++;
         }
         
          for(i=0;i<l1;i++)
         {
             if(hash[s1[i]]==0)
             s3=s3+s1[i];
         }
         cout<<s3<<endl;
         
    }
    return 0;
}

3 个答案:

答案 0 :(得分:1)

该程序确定第二个字符串中不包含第一个字符串中的哪些字符。

该程序的示例输入:

1
abcdefghijklmnopqrstuvwxyz
helloworld

示例输出(感谢@mch进行纠正)

abcfgijkmnpqstuvxyz

编辑:请注意,这当然是区分大小写的,因为字符aA会产生不同的整数值。

以下是关于该程序的一些评论:

#include <iostream>
using namespace std;
#include <string.h>
int main() {
    // Do the whole program as many times as the user says
    int t;
    cout << "enter any no. to run the loop" << endl;
    cin >> t;
    while (t--) {
        string s1, s2, s3;
        int i, j, l1, l2;
        // read strings and get their respective lengths
        cout << "enter two strings s1 and s2" << endl;
        cin >> s1 >> s2;
        l1 = s1.length();
        l2 = s2.length();

        // Array with 257 elements
        int hash[257];
        // Initialize all elements of array with 0
        for (i = 0; i < 257; i++) {
            hash[i] = 0;
        }

        // Count occurrences of characters in second string
        // s2[i] is the character at position i in s2
        // Increase the value of hash for this character by 1
        for (i = 0; i < l2; i++) {
            hash[s2[i]]++;
        }

        // Iterate over s1 characters
        // If hash[i] == 0: character i is not contained in s2
        // s3 => string of letters in s1 that are not contained in s2
        for (i = 0; i < l1; i++) {
            if (hash[s1[i]] == 0)
                s3 = s3 + s1[i];
        }

        // output s3
        cout << s3 << endl;
    }
    return 0;
}

答案 1 :(得分:0)

代码计算s1中字母出现的直方图,并复制出现次数为零的s2字母。

对于任何不限于范围char(!)的[0,256]类型,它都可能崩溃

答案 2 :(得分:0)

上面有一条注释解释了for循环。

int hash[257]实际上可以是int hash[256]char(8位)中可以容纳256个不同的值。