Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,941 questions

51,879 answers

573 users

How to remove all characters except alphabets from input string in C++

2 Answers

0 votes
#include <iostream>
#include <string>

using std::cout;
using std::endl;

int main()
{
	string s;
	
	cout << "Enter a string: ";
	getline(std::cin, s);

	for (int i = 0; i < s.size(); i++)
	{
		if (!((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')))
				s[i] = ' ';
	}
	cout << s << endl;
		
	return 0;
}

/*
run:

Enter a string: c,c++,7363"[java]
c c         java

*/

 



answered Jan 26, 2018 by avibootz
edited Feb 1, 2019 by avibootz
0 votes
#include <iostream>
#include <string>
#include <algorithm>

using std::cout;
using std::endl;
using std::string;

bool BothAreSpaces(char lhs, char rhs) { return (lhs == rhs) && (lhs == ' '); }

int main()
{
	string s;
	
	cout << "Enter a string: ";
	getline(std::cin, s);

	for (int i = 0; i < s.size(); ++i)
	{
		if (!((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')))
				s[i] = ' ';
	}
	
	// remove duplicate spaces
	string::iterator new_end = std::unique(s.begin(), s.end(), BothAreSpaces);
	s.erase(new_end, s.end());

	cout << s << endl;
		
	return 0;
}

/*
run:

Enter a string: c,c++,474"[java]
c c java

*/

 



answered Jan 26, 2018 by avibootz
edited Jan 27, 2018 by avibootz

Related questions

1 answer 127 views
1 answer 120 views
1 answer 120 views
3 answers 137 views
1 answer 132 views
...