Explaining code

Can someone please explain this line I can’t visualize what’s happening in this.

ans = string(1, s[i]) + string(1, s[i + 1]);

code link- Problem - B - Codeforces

	cin >> n;
	string s;
	cin >> s;
	
	int res = 0;
	string ans;
	for (int i = 0; i < n - 1; ++i) {
		int cur = 0;
		for (int j = 0; j < n - 1; ++j)
			if (s[j] == s[i] && s[j + 1] == s[i + 1])
				++cur;
		if (res < cur) {
			res = cur;
			ans = string(1, s[i]) + string(1, s[i + 1]);
		}
	}
	
	cout << ans << endl;
1 Like

There are multiple ways to declare a string.
string a creates an empty string “”.
string(4,'e') creates a string “eeee”.
string(1,'b') creates a string “b”.
Similarly, string(1, s[i]) + string(1, s[i+1]) is just s[i] and s[i+1] concatenated. Note that you cannot simply use the + operation on s[i] and s[i+1] because they are characters and + does not concatenate characters.

[EDIT] Another alternative to this is to_string(s[i]) + to_string(s[i+1]).

3 Likes

thank you so much sir. i learned something new. thank you explaining the code

Hey Hey! Please don’t call me sir. I’m just a fellow coder like you. Glad I could help :wink:.