有人能帮我理解这个c++代码吗

can anyone help me to understand this c++ code?

本文关键字:c++ 代码      更新时间:2023-10-16

我向您解释这个程序的工作原理。

步骤1:输入要运行循环的时间。

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

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

问题:我无法理解for循环的工作原理,以及为什么hash的值是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;
}

这个程序计算出第一个字符串中的哪些字符不包含在第二个字符串中。

程序输入示例:

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;
}

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

它可以为任何不限于[0,256](!(范围的char类型崩溃

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

CCD_ 7实际上可以是CCD_。有256个不同的值可以适合于char(8位(。