有人能帮我理解这个c++代码吗
can anyone help me to understand this c++ code?
我向您解释这个程序的工作原理。
步骤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
编辑:请注意,这当然是区分大小写的,因为字符a
和A
会产生不同的整数值。
以下是对该节目的一些评论:
#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位(。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值