我想比较两个String数组之间的值并计算重复的单词 我创建了二维数组: 第一维:包含所有单词, 第二维:包含计数器; 为此,我想将第二维的数据类型从String转换为int 计算重复。 我可以做这个转换????
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace change
{
class Program
{
static void Main(string[] args)
{
// int counter = 1;
String [] arr = {"aaa","bbb","ccc","ddd","eee","ddd","bbb"} ;
String[] arr2 = { "a", "bb", "ccc", "dd", "aaa", "fff", "ooo" };
String[,] wordsAndCounter = new string[arr.Length, 2]; // matrix contains [words, counter] . I want to convert counter datatype to int to calculate the repeated words .
for (int i = 0; i < arr.Length; i++) {
wordsAndCounter[i, 0] = arr[i];
// Console.WriteLine(wordsAndCounter[i,0]);
// Console.WriteLine(wordsAndCounter[i, 1]);
String x= arr[i];
String y = arr2[i];
// for (int j = 0; j < arr.Length; j++) {
if (x.Equals(y))
// {
counter++;
wordsAndCounter[i, 1] = "counter"; // i want to convert this "counter" to int
// Console.WriteLine(wordsAndCounter[i, 1]);
// Console.WriteLine(counter);
}
else {
wordsAndCounter[i, 1] = "counter"; // i want to convert this "counter" to int
// Console.WriteLine(wordsAndCounter[i, 1]);
// Console.WriteLine(counter);
}
}
}
Console.ReadLine();
}
} }
答案 0 :(得分:1)
要从字符串转换为int,您始终可以使用int.Parse
或(甚至更好)int.TryParse
。但是在您的示例中,您定义了字符串数组,因此您实际上需要向后转换 - 因此您可以使用ToString()
。你的方法的缺点是缺乏灵活性 - 你想要整数,而不是字符串,因此你可以使用dinamic对象或通用字典/元组列表/什么。这是一个带动态对象的简短LINQ解决方案:
String [] arr = {"aaa","bbb","ccc","ddd","eee","ddd","bbb"} ;
String[] arr2 = { "a", "bb", "ccc", "dd", "aaa", "fff", "ooo" };
var list = arr.Select(a => new {Word = a, WordCount = arr2.Count(a2 => a2 == a)}).ToList();
list.ForEach(el => Console.WriteLine(el.Word + " " + el.WordCount));
答案 1 :(得分:0)
如果我理解你想要的东西:
static void Main()
{
int counter = 1;
String [] arr = {"aaa","bbb","ccc","ddd","eee","ddd","bbb"} ;
String[] arr2 = { "a", "bb", "ccc", "dd", "aaa", "fff", "ooo" };
Dictionary<string, int> dict = new Dictionary<string, int> ();
for (int i = 0; i < arr.Length; ++i)
{
wordsAndCounter[i, 0] = arr[i];
string x = arr[i];
string y = arr2[i];
if (x.Equals(y)) {
if (dict.ContainsKey(x)) {
++dict[x];
} else {
dict[x] = 1;
}
}
}
foreach (var el in dict) {
Console.WriteLine("{0} {1}", el.Key, el.Value);
}
}