【发布时间】:2018-01-23 10:12:58
【问题描述】:
如果我第一次没有解释清楚,我深表歉意。我在下面用粗体进一步编辑了我的解释。
在下面的程序中,用户输入一个单词,然后输入一个用户想用任何字符替换的字母。例如,用户输入一个单词“Hello”,替换字母是“l”和“$”。所以“Hello”会变成“He$$o”。 首先,目标是找到“l”的位置(例如 - 2,3),然后替换该特定位置的元素。
我首先找到“l”的位置并将其存储在 findIndex 数组中。每次我运行程序时,我都会将“22222”存储在 findIndex[] 数组中。在这一点上,我什至不确定我是否应用了正确的逻辑。任何建议将被认真考虑!请不要使用 LINQ。
public static void RemoveSpecifiedCharacters()
{
Console.WriteLine("\nWrite a word/sentence: ");
string myString = Console.ReadLine();
Console.Write("Type the character you would like to replace: ");
string myCharacter = Console.ReadLine();
int[] findIndex = new int[myString.Length];
for (int i = 0; i < myString.Length; i++)
{
findIndex[i] = myString.IndexOf(myCharacter, 0);
}
for (int i = 0; i < findIndex.Length; i++)
{
Console.Write(findIndex[i]);
}
}
【问题讨论】:
-
这是你的目标吗?
user enter's a word "Hello" and the replacement letter is "l" with "$". So "Hello" will become "He$$o".然后试试String.Replace() -
IndexOf 方法的第二个参数是搜索的起始索引 - 您总是从索引 0 开始,所以它总是会在第三个字符 (index=2) 处找到“l”。目前尚不清楚您在第一个循环中实际尝试做什么。您是否尝试创建角色出现的位置数组?如果这是您想要的,那么这里的示例可能会对您有所帮助:msdn.microsoft.com/en-us/library/…