用java統計乙個字串中重複出現的單詞的個數

時間 2021-06-25 08:32:04

1樓:Janyee

按照 @林習習提供的思路用 C# 寫了乙個,只不過這裡用的是自己實現的鍊錶(Repostory)而不是 Map:

using

System

;using

System.Collections.Generic

;using

System.Linq

;namespace}}

foreach

(var

item

inrepeatWordStatistically

) 在文中出現了 次");}

Console

.ReadKey();

}}////// 字串解析工具類

///static

class

Parser

;// 查詢出不符合寫入 token 的字元的查詢指令

varnotEligibleQuery

=from

@char

intext

where

split

(@char

)select

new;

Repostory

,char

>repo=(

notEligibleQuery

);return

Parser

.Split

(text

,repo

.ToArray()

);}////// 執行 notEligibleQuery 查詢,並把它儲存到 Repostory 中(每個字元僅儲存一次,鍵-值唯一性)

////// 查詢不符合寫入 token 的字元的查詢指令

private

static

Repostory

,char

>(IEnumerable

>notEligibleQuery)}

catch

(NullReferenceException)}

return

repo;}

////// 返回乙個包含了由指定的字元陣列的元素分割出來的子字串的字串陣列

////// 執行分割的字串源

/// 指定分割字元的分割器

///private

static

string[]

Split

(string

source

,params

char[]

separator

)substring

[substring

.Length-1

]+=source

[index];}

else

}else

else}}

else

}return

substring;}

}///

/// int 型別的自定義封裝類,也是泛型類 Repostory 的型別引數的約束型別,

/// 該類的設計目的是為了解決 Repostory 中使用了型別引數的成員無法使用運算子的問題。

///class

Integer

public

static

implicit

operator

int(

Integer

integer

)=>integer

._data

;public

static

implicit

operator

Integer

(int

@int

)=>newInteger

(@int

);public

static

bool

operator

==(Integer

left

,Integer

right

)public

static

bool

operator

!=(Integer

left

,Integer

right

)public

override

bool

Equals

(object

obj)

public

override

intGetHashCode()

public

override

string

ToString()

}///

/// 該類是乙個鍊錶,使用鍵/值結構來儲存 notEligibleQuery 查詢出來的字元及其在資料來源中的索引

////// 鍵的型別

/// 值的型別

class

Repostory

whereK:

Integer

}private

V_value

;public

VValue

}private

int_count

;public

intCount

}private

Repostory

_node

;///

/// 返回當前節點的子節點

///public

Repostory

Node

}public

Repostory()

public

Repostory(K

k,Vv

)///

/// 新增乙個節點

/////////public

void

Add(

Kkey,V

value

)else

this

._count

++;}

////// 確定容器是否存在某節點的值

/////////public

bool

Contains(V

value)}

return

false;}

catch

(NullReferenceException)}

////// 獲取乙個迭代器

//////public

IEnumerator

>GetEnumerator()

}else

}///

/// 把整個 Repository 轉換成陣列

//////publicV[

]ToArray()

return

arr;

}///

/// 鍵索引器,返回鍵對應的值

/////////public

Vthis[K

key]

else

}throw

newInvalidOperationException

("元素不存在。");}}}}

python如何統計乙個字串中各字元的數量?

Shreck Ye 其實因為字符集是已知而且連續的,直接按字元編碼對映到乙個記憶體陣列裡面效率要比字典更高。不過既然是Python,變數都是用字典存的,效率似乎就無所謂了,更重要的是怎麼寫更簡單更快。這裡用字典也更方便簡單,參照高讚答案用collections.Counter一行就可以解決更好。 2...

C語言,用陣列定義乙個字串,那這個字串是怎麼儲存在這個陣列中的呢?

the gc 對於scanf的 s的解釋如下 Matches a sequence of non white space characters the nextpointer must be a pointer to the initial element of acharacter array t...

怎麼用python統計字串中每個字元出現的次數?

酒罈壇兒 str1 hello world 方法一 字典推導式 result print result 方法二 自己寫邏輯 result forx instr1 result x result get x 0 1print result 拯救夢想 實現的這個功能的方法實在太多,python 內建的包...