Write a C++ program to sort characters (numbers and punctuation symbols are not included) in a string

  • برمجة سي بلس بلس
  • برمجة

Write a C++ program to sort characters (numbers and punctuation symbols are not included) in a string

Sample Output:

Original text: python 
Sorted text: hnopty

Original text: AaBb 
Sorted text: ABab

الأجوبة

#include <iostream>
#include <string>

using namespace std;

string sort_characters(string text) {

	bool flag;
	char ch;

	do
	{
		flag = false;

		for (int x = 0; x < text.length() - 1; x++)
		{
			if (text[x] > text[x + 1])
			{
				ch = text[x];
				text[x] = text[x + 1];
				text[x + 1] = ch;
				flag = true;
			}
		}
	} while (flag);

	// Remove spaces
	string str;
	for (int y = 0; y < text.length(); y++)
	{
		if (text[y] != ' ')
		{
			str.push_back(text[y]);
		}
	}

	return str;
}

int main() {

	cout << "Original text: python \nSorted text: ";
	cout << sort_characters("python") << endl;
	cout << "\nOriginal text: AaBb \nSorted text: ";
	cout << sort_characters("AaBb") << endl;
	cout << "\nOriginal text: the best way we learn anything is by practice and exercise questions \nSorted text: ";
	cout << sort_characters("the best way we learn anything is by practice and exercise questions") << endl;
	return 0;

}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...