#java #c#
#java #c#
Вопрос:
Я использую этот код для сходства предложений, код доступен на Java, я хочу использовать это в c #.
public static int getWordChanges(String s1, String s2) {
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
s2 = s2.toLowerCase().replace(".", "").replace(",", "").replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.split(" ").length; i ) {
boolean exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.split(" ").length; j ) {
//Is the word misspelled?
if ((getLevenshteinDistance(s1.split(" ")[i], s2.split(" ")[j]) * 100 / s1.split(" ")[i].length()) < similarityThreshold) {
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists) {
wordChanges ;
}
}
return wordChanges;
}
Это Java-код, который я хочу выполнить на c#
После преобразования кода в c#
public int getWordChanges(String s1, String s2)
{
int similarityThreshold = 50;
int wordChanges = 0;
s1 = s1.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
s2 = s2.ToLower().Replace(".", "").Replace(",", "").Replace(";", "");
//Loop through each word in s1
for (int i = 0; i < s1.Split(' ').Length; i )
{
bool exists = false;
//Search for i'th word in s1 in s2
for (int j = 0; j < s2.Split(' ').Length; j )
{
//Is the word misspelled?
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
{
exists = true;
break;
}
}
//If the word does not exist, increment wordChanges
if (!exists)
{
wordChanges ;
}
}
return wordChanges;
}
}
}
В этой строке ошибка
if ((getLevenshteinDistance(s1.Split(' ')[i], s2.Split(' ')[j]) * 100 / s1.Split(' ')[i].Length()) < similarityThreshold)
ошибка длины покажет, как я решаю эту проблему
Комментарии:
1. Длина — это свойство, а не метод. Измените его на
.Length
вместо.Length()
Ответ №1:
Добавьте эту функцию в свой проект
public static int getLevenshteinDistance(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n 1, m 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i )
{
}
for (int j = 0; j <= m; d[0, j] = j )
{
}
// Step 3
for (int i = 1; i <= n; i )
{
//Step 4
for (int j = 1; j <= m; j )
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] 1, d[i, j - 1] 1),
d[i - 1, j - 1] cost);
}
}
// Step 7
return d[n, m];
}
И измените .Length() to .Length
, потому что строка.Длина — это свойство, а не метод