Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. bool firstUniqueChar(std::string &, char &);
  4. int main()
  5. {
  6.     //line read from input
  7.     std::string line;
  8.     //word in read line
  9.     std::string word;
  10.     //the result of processing words, which contains all first unique characters in words
  11.     std::string half_result;
  12.     int pos;
  13.     //the input can consist of one or more lines, so we'll process them all
  14.     for(;std::getline(std::cin, line);)
  15.     {
  16.         //find the position of next ' '
  17.         //if no matches were found, find returns string::npos
  18.         while((pos = line.find(" ")) != std::string::npos)
  19.         {
  20.             //current word
  21.             word = line.substr(0, pos);
  22.             //cut this word including first ' ' from input string
  23.             line.erase(0, pos + 1);
  24.             //the input word can be empty. in this case we'll not process it
  25.             if(!word.empty())
  26.             {
  27.                 char c;
  28.                 if(firstUniqueChar(word, c))
  29.                     half_result.append(1, c);
  30.             }
  31.         }
  32.         //the rest of the line contains last word
  33.         //it also can be empty
  34.         if(!line.empty())
  35.         {
  36.             char c;
  37.             if(firstUniqueChar(word, c))
  38.                 half_result.append(1, c);
  39.         }
  40.     }
  41.     char c;
  42.     if(!half_result.empty() && firstUniqueChar(half_result, c))
  43.            std::cout<<std::endl<<c<<std::endl;
  44.     else
  45.             std::cout<<"<nothing>"<<std::endl;
  46.     return 0;
  47. }
  48.  
  49. bool firstUniqueChar(std::string &word, char &c)
  50. {
  51.     for(std::string::iterator it = word.begin(); it != word.end(); ++it)
  52.     {
  53.         //find occurence of current char in string Before current position
  54.         int posB = (std::distance(word.begin(), it)) != 0 ? word.rfind(*it, std::distance(word.begin(), it) - 1) : std::string::npos;
  55.         //find occurence of current char in string After current position
  56.         int posA = (std::distance(word.begin(), it)) != word.size() - 1 ? word.find(*it, std::distance(word.begin(), it) + 1) : std::string::npos;
  57.         if(posA == std::string::npos && posB == std::string::npos){
  58.             c = *it;
  59.             return true;
  60.         }
  61.     }
  62.     return false;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement