21xrx.com
2024-09-20 00:46:57 Friday
登录
文章检索 我的文章 写文章
C++中的最长和最短单词
2023-07-09 11:05:16 深夜i     --     --
C++ 最长单词 最短单词 字符串处理 搜索算法

在C++中,有时候我们需要找到字符串中的最长和最短单词。这个问题可以通过使用C++语言中的字符串处理函数来解决。

首先,我们需要将字符串拆分成单个单词,然后比较单词的长度,找出最长和最短的单词。C++中有很多字符串处理函数可以实现这个功能,其中最常用的函数是split()和substr()。

split()函数是将字符串分解成单个单词的函数。这个函数需要两个参数:第一个参数是要分解的字符串,第二个参数是分隔符。分隔符可以是一个空格或一个标点符号。例如,下面的代码将一个字符串分解为单个单词,并将它们存储在一个向量中。


#include <iostream>

#include <string>

#include <vector>

using namespace std;

vector<string> split(string str, char sep) {

  vector<string> words;

  string word;

  for (int i = 0; i < str.length(); i++) {

    if (str[i] != sep) {

      word += str[i];

    } else {

      words.push_back(word);

      word = "";

    }

  }

  words.push_back(word);

  return words;

}

int main() {

  string str = "Hello, World! This is a test.";

  vector<string> words = split(str, ' ');

  for (int i = 0; i < words.size(); i++) {

    cout << words[i] << endl;

  }

  return 0;

}

substr()函数是一个提取子字符串的函数。它需要两个参数:第一个参数是字符串的起始位置,第二个参数是要提取的子字符串的长度。例如,下面的代码提取一个字符串的子字符串。


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = "Hello, World!";

  string sub_str = str.substr(0, 5);

  cout << sub_str << endl;

  return 0;

}

现在,我们可以将这两个函数结合起来,找到一个字符串中的最长和最短单词。对于每个单词,我们可以使用substr()函数计算它的长度,并将长度与当前的最长和最短单词的长度进行比较。如果它是最长或最短的单词,我们将更新最长和最短单词的值。

让我们来看一下下面的代码:


#include <iostream>

#include <string>

#include <vector>

using namespace std;

vector<string> split(string str, char sep) {

  vector<string> words;

  string word;

  for (int i = 0; i < str.length(); i++) {

    if (str[i] != sep) {

      word += str[i];

    } else {

      words.push_back(word);

      word = "";

    }

  }

  words.push_back(word);

  return words;

}

int main() {

  string str = "The quick brown fox jumps over the lazy dog.";

  vector<string> words = split(str, ' ');

  string longest_word = words[0];

  string shortest_word = words[0];

  for (int i = 0; i < words.size(); i++) {

    if (words[i].length() > longest_word.length()) {

      longest_word = words[i];

    }

    if (words[i].length() < shortest_word.length()) {

      shortest_word = words[i];

    }

  }

  cout << "Longest word: " << longest_word << endl;

  cout << "Shortest word: " << shortest_word << endl;

  return 0;

}

输出将会是:


Longest word: jumps

Shortest word: The

在上面的代码中,我们首先将字符串分解为单个单词,然后使用for循环遍历这些单词。在遍历单词时,我们使用if语句比较单词的长度,并将其与当前的最长和最短单词进行比较。如果它是最长或最短的单词,我们将更新最长和最短单词的值。最后,我们使用cout语句输出最长和最短单词。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复