所以目前我正在處理一段代碼,其中給了我一個字串,需要計算字串中每個字符出現的次數,如果它只出現一次,用 ax 替換它,如果它出現不止一次,用 a是的。例如:“分數”=>“yxxxxy”。
我目前的代碼是
public static string changeWord(string word)
{
var Pl = word;
var pj = Pl;
string alpha = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < alpha.Length; i )
{
var count = word.Count(x => x == alpha[i]);
Console.WriteLine(count);
if (count > 1)
{
Pl = word.Replace(alpha[i], 'y');
}
else if (count == 1)
{
Pl = word.Replace(alpha[i], 'x');
}
}
return Pl;
}
計數有效并顯示每個字母的正確計數,但僅更改代碼中的最后一個,因此“請”=>“請”我不知道如何獲取 .replace 以保留我的新字串。
uj5u.com熱心網友回復:
有一個問題Replace演算法:一旦將信函轉換給x您,則應x自行處理信函,例如
initial: box
after 'b' processed: xox
after 'o' processed: xxx # note, that x appeared 3 times now
after 'x' processed: yyy
after 'y' processed: yyy # we have 3 y's so they changed to themselves
finally: yyy # when xxx is expected
這就是為什么word我建議使用StringBuilder并構建新字串而不是更改現有字串:
public static string changeWord(string word) {
if (string.IsNullOrEmpty(word))
return word;
StringBuilder sb = new StringBuilder(word);
for (int i = 0; i < sb.Length; i)
if (sb[i] >= 'a' && sb[i] <= 'z')
sb[i] = word.Count(c => c == sb[i]) > 1 ? 'y' : 'x';
return sb.ToString();
}
在long word的情況下,太多Count可能會很耗時;您可以嘗試快取它們:
public static string changeWord(string word) {
if (string.IsNullOrEmpty(word))
return word;
StringBuilder sb = new StringBuilder(word);
Dictionary<char, int> counts = new Dictionary<char, int>();
for (int i = 0; i < sb.Length; i)
if (sb[i] >= 'a' && sb[i] <= 'z') {
if (!counts.TryGetValue(sb[i], out int count)) {
count = word.Count(c => c == sb[i]);
counts.Add(sb[i], count);
}
sb[i] = count > 1 ? 'y' : 'x';
}
return sb.ToString();
}
uj5u.com熱心網友回復:
試試這個:
public static string changeWord(string word)
{
string alpha = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < alpha.Length; i )
{
var count = word.Count(x => x == alpha[i]);
Console.WriteLine(count);
if (count > 1)
{
word = word.Replace(alpha[i], 'y');
}
else if (count == 1)
{
word = word.Replace(alpha[i], 'x');
}
}
return word;
}
uj5u.com熱心網友回復:
這種方法使你想要的作業
public static string changeWord(string word)
{
var wordToEdit = word;
string alpha = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < alpha.Length; i )
{
var count = word.Count(x => x == alpha[i]);
if (count > 0)
{
wordToEdit = wordToEdit.Replace(alpha[i], count == 1 ? 'x' : 'y');
}
}
return wordToEdit;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/461269.html
下一篇:如何制作一個二維陣列進行迭代?
