acronyms using find()

Using the find() function, how do I find the acronym of an inputted string? The program would find the first letter of each string, put all leading letters in one string, and display it. For example, an input of "this is a test input" would output "tiati". An input of "national aeronautics space administration" would output "nasa".

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <vector>
#include <cctype>  
using namespace std;  

int main()  {
  string text;
  cout<<"Enter text";
  getline(cin, text);
  //using the find() function find the first letter of each string to find the acronym
  cout<<"Acronym: ";
}
Last edited on
Hello coder0101,

You could use the "find" function, but I think that "find_first_not_of" may be a better choice.

You could also use a for loop.

Andy

You might like stringstream as well if find is optional.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string badd = "A Criminal Regiment of Nasty Young Men";
    stringstream ss;
    ss << badd;
    string temp;
    while(ss >> temp)
    {
        cout << temp[0];
    }
    cout << endl;
}


Otherwise print the first letter in the line, then use find to find the next whitespace and print the next letter after that. Rinse and repeat.
You should end this loop when the result is string::npos

https://www.cplusplus.com/reference/string/string/find/
Last edited on
Using stringstream:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <sstream>

int main()
{
	std::string text;

	std::cout << "Enter text: ";
	std::getline(std::cin, text);

	std::istringstream ss(text);

	for (std::string s; ss >> s; std::cout << s.front());

	std::cout << '\n';
}


or using find_if/find_if_not:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main()
{
	std::string text;

	std::cout << "Enter text: ";
	std::getline(std::cin, text);

	for (auto it = text.begin(); (it = std::find_if_not(it, text.end(), [](char ch) {return std::isspace(ch); })) != text.end(); it = std::find_if(it, text.end(), [](char ch) { return std::isspace(ch); }))
			std::cout << *it;

	std::cout << '\n';
}



Enter text: national aeronautics space administration
nasa

Last edited on
Topic archived. No new replies allowed.