好的,所以我创建了一个包含带有一些for循环的字符串/ int数组的代码。在我的代码中有一个部分,它的字符串数超过1,但如果有多个字符串,你如何使字符串复数?这是我正在谈论的代码的一部分:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VoidFunctions : MonoBehaviour
{
public string[] Enemies = {"Ghoul", "Skeleton", "Zombie"};
public int[] enemyCount = {1, 2, 2};
public virtual void Start()
{
for (int i = 0; i < Enemies.Length; i++)
{
Fight(Enemies[i], enemyCount[i]);
}
}
void Fight(string enemy, int amount)
{
print(this.name + " encountered a " + enemy);
print(this.name + " killed " + amount + " " + enemy);
}
}
所以对于第二个字符串“Skeleton”,有2个被杀,但它出来了“被杀2个骷髅”......你怎么把它复数?
答案 0 :(得分:2)
正如Ness Rosales所说,您可以使用复数化软件或转换图表。虽然对于这种类型的项目,如果您有不到20个项目,我会考虑使用此类软件过度杀伤。
我要做的是改变敌人阵列,使每个名词都有单数和复数形式:
public string[][2] Enemies =
{
{“Ghoul”, ”Ghouls”}, {“Skeleton”, “Skeletons”}, {“Zombie”, “Zombies”}
};
从这里开始,您可以根据数量制作if
/ else
语句,以获取每个名词的字符串0或1。
答案 1 :(得分:2)
有多种方法可以实现这一目标:
s
(依赖于西方语言)PluralizationService
的强大方式
代码:
using System;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;
namespace WindowsFormsApp1
{
internal class MyClass
{
private static void CheckParameters(string word, int count)
{
if (string.IsNullOrWhiteSpace(word))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(word));
if (count <= 0)
throw new ArgumentOutOfRangeException(nameof(count));
}
public static string GetLabel1(string word, int count)
{
CheckParameters(word, count);
var label = $"{word}{(count > 1 ? "s" : string.Empty)}";
return label;
}
public static string GetLabel2(string word, int count)
{
CheckParameters(word, count);
// TODO this should be a member instead of being instantiated every time
var service = PluralizationService.CreateService(CultureInfo.CurrentCulture);
var label = count > 1 ? service.Pluralize(word) : service.Singularize(word);
return label;
}
}
}