You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#中如何统计具有特定值的字符串数量?

统计指定字符串的出现次数

手动统计实现

如果不想依赖内置工具,可以用字典手动完成计数:

  • 初始化空字典存储每个字符串的出现次数
  • 遍历目标字符串列表,更新对应字符串的计数
# 定义目标字符串列表
strings = ["stack", "stack", "overflow", "problem"]
count_dict = {}

# 遍历统计
for s in strings:
    if s in count_dict:
        count_dict[s] += 1
    else:
        count_dict[s] = 1

# 获取指定字符串的计数
print(count_dict["stack"])    # 输出:2
print(count_dict["overflow"]) # 输出:1
print(count_dict["problem"])  # 输出:1

用内置工具简化实现

Python的collections.Counter是专门用于计数的工具类,能更简洁地完成需求:

from collections import Counter

strings = ["stack", "stack", "overflow", "problem"]
counter = Counter(strings)

# 获取指定字符串的计数
print(counter["stack"])    # 输出:2
print(counter["overflow"]) # 输出:1
print(counter["problem"])  # 输出:1

# 查看所有字符串的计数结果
print(counter) # 输出:Counter({'stack': 2, 'overflow': 1, 'problem': 1})

内容的提问来源于stack exchange,提问作者f0rCE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:34:52