文字列中の単語出現回数をカウントする方法:Python, C++, Java, C#
この記事では、文字列中に特定の単語が何回出現するかを数える方法を解説します。プログラミング初心者にもわかりやすいように、様々な言語での実装例を紹介し、それぞれのコードについて詳しく説明します。
方法1:文字列を分割して比較する
この方法は、文字列をスペースで分割し、単語のリストを作成します。その後、リスト内の各要素を目的の単語と比較し、一致する回数をカウントします。
C++での実装
// C++ program to count the number
// of occurrence of a word in
// the given string
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int countOccurrences(string str, string word) {
stringstream ss(str);
string token;
int count = 0;
while (ss >> token) {
if (token == word) {
count++;
}
}
return count;
}
int main() {
string str = "GeeksforGeeks A computer science portal for geeks";
string word = "portal";
cout << countOccurrences(str, word) << endl;
return 0;
}
Cでの実装
// C program to count the number
// of occurrence of a word in
// the given string
#include <stdio.h>
#include <string.h>
int countOccurrences(char *str, char *word) {
char *p;
int count = 0;
p = strtok(str, " ");
while (p != NULL) {
if (strcmp(word, p) == 0) {
count++;
}
p = strtok(NULL, " ");
}
return count;
}
int main() {
char str[] = "GeeksforGeeks A computer science portal for geeks";
char word[] = "portal";
printf("%d\n", countOccurrences(str, word));
return 0;
}
Javaでの実装
// Java program to count the number
// of occurrence of a word in
// the given string
import java.io.*;
class GFG {
static int countOccurrences(String str, String word) {
// split the string by spaces in a
String a[] = str.split(" ");
// search for pattern in a
int count = 0;
for (int i = 0; i < a.length; i++) {
// if match found increase count
if (word.equals(a[i]))
count++;
}
return count;
}
// Driver code
public static void main(String args[])
{
String str = "GeeksforGeeks A computer science portal for geeks ";
String word = "portal";
System.out.println(countOccurrences(str, word));
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3での実装
# Python program to count the number of occurrence
# of a word in the given string
def countOccurrences(str, word):
# split the string by spaces in a
a = str.split(" ")
# search for pattern in a
count = 0
for i in range(0, len(a)):
# if match found increase count
if (word == a[i]):
count = count + 1
return count # Driver code
str = "GeeksforGeeks A computer science portal for geeks "
word = "portal"
print(countOccurrences(str, word))
C#での実装
// C# program to count the number
// of occurrence of a word in
// the given string
using System;
class GFG
{
static int countOccurrences(string str,
string word)
{
// split the string by spaces
string [] a = str.Split(' ');
// search for pattern in string
int count = 0;
for (int i = 0; i < a.Length; i++)
{
// if match found increase count
if (word.Equals(a[i]))
count++;
}
return count;
}
// Driver code
public static void Main()
{
string str = "GeeksforGeeks A computer science portal for geeks ";
string word = "portal";
Console.Write(countOccurrences(str, word));
}
}
// This code is contributed
// by ChitraNayal
Javascriptでの実装
PHPでの実装
<?php
// PHP program to count the number
// of occurrence of a word in
// the given string
function countOccurrences( $str , $word )
{
// split the string by spaces
$a = explode(" ", $str );
// search for pattern in string
$count = 0;
for ( $i = 0; $i < sizeof( $a ); $i ++)
{
// if match found increase count
if ( $word == $a [ $i ])
$count ++;
}
return $count ;
}
// Driver code
$str = "GeeksforGeeks A computer science portal for geeks ";
$word = "portal";
echo (countOccurrences( $str , $word ));
// This code is contributed
// by ChitraNayal
?>
この方法の**時間計算量はO(n)**です。ここで、nは文字列の長さです。文字列をスペースで分割するのにO(n)の時間が必要であり、リストを反復処理してカウントするのにO(n)の時間が必要です。**補助空間はO(n)**です。
方法2:Pythonのcount()
関数を使用する
この方法は、文字列をスペースで分割してリストに格納し、そのリストに対してPythonの組み込み関数であるcount()
を使用して、指定された単語の出現回数をカウントします。
def countOccurrences(str, word):
wordslist = list(str.split())
return wordslist.count(word)
str = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
print(countOccurrences(str, word))
ここでは、Java、C++、C#の場合と同じように単語リスト全体を反復処理する代わりに、Pythonのcount()関数を使用しているため、コードを作成するためのより簡潔な方法です。
この方法の**時間計算量はO(n)**です。ここで、nは文字列の長さです。文字列をスペースで分割するのにO(n)の時間がかかり、リストの長さは文字列の長さまでになる可能性があり、count()関数はO(n)の時間でリスト全体を反復処理するため、合計で時間計算量はO(n)のオーダになります。
空間計算量は**補助空間O(n)**です。文字列をスペースで分割し、結果をリストwordslistとして格納するために文字列のサイズに比例する追加空間を必要とします。
方法3:re.findall
モジュールを使用する
この方法は、Pythonのre
(正規表現)モジュールを利用して、文字列から目的の単語を抽出します。re.findall()
関数は、文字列内でパターンに一致するすべての文字列をリストとして返します。
import re
def count_word_occurrences2(string, word):
return len(re.findall(word, string))
string = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
count = count_word_occurrences2(string, word)
print(f"Occurrences of Word = {count} Time")
この関数は、指定された文字列内でreモジュールを使用して、指定された単語の不重畳の出現箇所をすべて探し出し、それらの出現回数を返します。
C++での実装
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int count_word_occurrences2(const string& str, const string& word) {
// 正規表現を使用して、文字列内の単語の出現箇所をすべて見つける
regex regex_word(word);
sregex_iterator it(str.begin(), str.end(), regex_word);
sregex_iterator end;
// 出現箇所の数を計算する
int count = 0;
while (it != end) {
count++;
++it;
}
return count;
}
int main() {
string str = "GeeksforGeeks A computer science portal for geeks";
string word = "portal";
int count = count_word_occurrences2(str, word);
cout << "Occurrences of Word = " << count << " Time" << endl;
return 0;
}
Javaでの実装
import java.util.regex.*;
public class WordOccurrences {
public static int countWordOccurrences(String str, String word) {
// 正規表現を使用して、文字列内の単語の出現箇所をすべて見つける
Pattern pattern = Pattern.compile("\\b" + Pattern.quote(word) + "\\b");
Matcher matcher = pattern.matcher(str);
// 出現箇所の数を計算する
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
public static void main(String[] args) {
String str = "GeeksforGeeks A computer science portal for geeks";
String word = "portal";
int count = countWordOccurrences(str, word);
System.out.println("Occurrences of Word = " + count + " Time");
}
}
時間計算量: O(nm) このアプローチでの時間計算量は、O(nm)のオーダになります。ここで、nはテキストの長さ、mは検索される単語の長さです。
空間計算量: O(1) このアプローチでの空間計算量は、O(1)のオーダになります。正規表現エンジンは、テキストまたはパターンサイズに比例する有意な追加の空間を通常必要としません。これは、パターンから定数の空間のみを必要とするからです。
まとめ
この記事では、文字列中の単語出現回数をカウントする3つの方法を紹介しました。それぞれの方法には異なる特徴があり、状況に応じて最適な方法を選択できます。
- 簡単な方法: 文字列を分割して比較する
- Pythonならではの方法:
count()
関数を使用する - 柔軟な方法:
re.findall
モジュールを使用する
これらの方法を理解することで、文字列操作に関するスキルを向上させ、より効率的なプログラミングが可能になります。