2016-04-30 3 views
0

Мне нужна помощь. У меня есть функция, которая печатает длинное слово в предложении. Но как отобразить кратчайшее слово?Как найти кратчайшее слово в строке C++

строка текст = «Меня зовут Боб»;

void LongestWord(string text) 
{ 
string tmpWord = ""; 
string maxWord = ""; 

for(int i=0; i < text.length(); i++) 
{ 
    /// If founded space, rewrite word 
    if(text[i] != ' ') 
     tmpWord += text[i]; 
    else 
     tmpWord = ""; 
    /// All the time check word length and if tmpWord > maxWord => Rewrite. 
    if(tmpWord.length() > maxWord.length()) 
     maxWord=tmpWord; 
} 
cout << "Longest Word: " << maxWord << endl; 
cout << "Word Length: " << maxWord.length() << endl; 
} 
+0

предполагая этот код правильно вы просто должны обменять 'если (tmpWord.length()> maxWord.length()) maxWord = tmpWord;' 'с, если (tmpWord.length() user463035818

+0

Я пробовал этот вариант. К сожалению, это не сработает :( – TomRay

+1

Почему это не работает? Вы должны показать свою попытку и сообщения об ошибках, которые вы получаете – user463035818

ответ

0
void ShortestWord(string text) 
{ 
string tmpWord = ""; 
// The upper bound of answer is text 
string minWord = text; 

for(int i=0; i < (int)text.length(); i++) 
{ 
    /// If founded space, rewrite word 

    if(text[i] != ' ') 
    { 
     tmpWord += text[i]; 
    } 
    else 
    { 
     // We got a new word, try to update answer 
     if(tmpWord.length() < minWord.length()) 
      minWord=tmpWord; 
     tmpWord = ""; 
    } 

} 
// Check the last word 
if(tmpWord != "") 
{ 
    if(tmpWord.length() < minWord.length()) 
     minWord=tmpWord; 
} 
cout << "Shortest Word: " << minWord << endl; 
cout << "Word Length: " << minWord.length() << endl; 
} 
1

Предложение приведены в разделе комментариев будет работать, это просто вопрос переставляя свои структуры управления, чтобы сделать его работу. т.е.

for(int i=0; i < text.length(); i++) 
{ 
    /// If founded space, rewrite word 
    if(text[i] != ' ') 
     tmpWord += text[i]; 
    else 
    { 
     if(minWord.length()==0)//this only happens once 
       minWord=tmpWord;//for the first word,you need to assign minWord so you have something to compare to 

     if(tmpWord.length() < minWord.length())//move this block here 
      minWord=tmpWord; 

     tmpWord = ""; 
    } 

} 

Я мог бы добавить, вы можете проверить слова гораздо легче, если вы использовали istringstream с извлечением operator>>. Что-то вроде:

#include <sstream> 
    .... 

    string text="my name is bob"; 
    string tmpWord = ""; 
    string minWord = ""; 
    istringstream ss(text);//defines the input string stream and sets text in the input stream buffer 

    while(ss.peek()!=EOF)//until the end of the stream 
    { 
     ss>>tmpWord;//read a word up to a space 

     if(minWord.length()==0)//this only happens once 
       minWord=tmpWord; 

     if(tmpWord.length() < minWord.length()) 
      minWord=tmpWord; 

    } 
1
void ShortestWord(std::string const& text) 
{ 
    std::stringstream ss(text); 
    std::vector<std::string> v(std::istream_iterator<std::string>(ss), {}); 
    auto min = std::min_element(v.begin(), v.end(), 
       [] (auto& lhs, auto& rhs) { return lhs.size() < rhs.size(); }); 
    auto p = std::make_pair(*min, min->size()); 
    std::cout << "Shortest Word: \"" << p.first << "\"\n"; 
    std::cout << "Word Length: " << p.second << '\n'; 
} 
+0

Всегда есть короткий и лучший способ делать что-то, не существует !! +1 –

+0

1) Сравнение по умолчанию сравнивает строки лексикографически: «aaa» меньше «c». 2) 'istream_iterator' является итератором ввода, а' min_element' требует, по крайней мере, переадресации. –

+0

@Revolver_Ocelot Обновлено. – 0x499602D2

0

Если мы хотим получить как минимальное значение и максимальное значение, значения Инициализировать должны быть противоположны к каждому из них. На самом деле это должна быть максимальная строка текста.
В разработке бизнес-приложения это здравый смысл, но некоторые программисты могут ненавидеть способ этого.

string minWord = text; // MAX_SIZE 
string maxWord = ""; 

for(int i = 0; i < text.length(); i++) 
{ 
    /// If founded space, rewrite word 
    if(text[i] != ' ') 
     tmpWord += text[i]; 

    if(text[i] == ' ' || i == text.length()) { 
     /// All the time check word length and if tmpWord > maxWord => Rewrite. 
     if(tmpWord.length() > maxWord.length()) 
      maxWord = tmpWord; 
     if(tmpWord.length() < minWord.length()) 
      minWord = tmpWord; 

     tmpWord = ""; 
    } 
} 
Смежные вопросы