我有一個申請
namespace Aplikacija1
{
public class excercise5
{
static void Main(string[] args)
{
Console.WriteLine("Enter word :");
string word = Console.ReadLine();
Console.WriteLine("Enter the letter :");
string letter = Console.ReadLine();
int charPos = word.IndexOf($"{letter}");
Console.WriteLine(word.Remove(charPos, 1));
}
}
}
所以它應該從輸入的字串中洗掉一個字母。
如果我輸入單詞 Nikola 和字母 a,結果是 Nikol,這是正確的
但是,如果我輸入單詞 Nikala 和字母 a,則結果是 Nikla,無法選擇洗掉第二個 a,或選擇要洗掉的 a
有沒有辦法在我的代碼中添加一些東西以使其作業?
uj5u.com熱心網友回復:
您可以使用該Replace()方法并將其替換為空字串:
string wordWithoutLetter = word.Replace(letter, "");
Console.WriteLine(wordWithoutLetter);
uj5u.com熱心網友回復:
C.Evenhuis 已經告訴你你需要做什么才能得到你想要的結果,但我只是想指出為什么你的第一次嘗試沒有奏效。
Remove,就你使用它的方式而言,就像是一種簡短的說法RemoveEverythingAfter- 它用于從字串中切割出大部分,并且類似于Substring. 它通常不用于重復洗掉單個字符或小部件。它切除并丟棄一部分字串,而Substring切除并保留部分字串
將字串索引視為在字母之間:
h e l l o _ w o r l d
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
0 1 2 3 4 5 6 7 8 9 1011
如果您說它Remove(7)將從 7 開始洗掉所有內容(向右,因此,8、9 ...):
h e l l o _ w o r l d
^^^^^^^^^^^^^ ^^^^^^^
Keep Remove
var hw = "hello_world";
Console.Print(hw.Remove(7)); //prints: hello_w
如果你說,Substring(7)它保持了從7日起
h e l l o _ w o r l d
^^^^^^^^^^^^^ ^^^^^^^
Remove Keep
var hw = "hello_world";
Console.Print(hw.Substring(7)); //prints: orld
Substring并且Remove還有一種形式,其中他們采用第二個引數來表示要保留或洗掉的字符數
如果你Substring(4, 3)說它保持索引 4 的長度為 3,那么將字符保持在 4 和 7 之間。如果你說它Remove(4, 3)洗掉了 4 和 7 之間的 3 個字符
h e l l o _ w o r l d
^^^^^^^ ^^^^^ ^^^^^^^ Substring(4, 3)
Remove Keep Remove --> result: o_w
h e l l o _ w o r l d
^^^^^^^ ^^^^^ ^^^^^^^ Remove(4, 3)
Keep Remove Keep --> result: hellorld
全部,Remove并不是您真正想要的,因為它用于洗掉范圍,而不是所有出現的字符/字串
for(var idx = word.IndexOf(letter); idx > -1; idx = word.IndexOf(letter))
word = word.Remove(idx, 1);
腳注:現代 C# 有另一種更緊湊的方式來執行 Substring 只使用索引:
var hw = "hello_world";
hw[4..] //keep from index 4 to end, i.e. o_world
hw[..4] //keep from start to index 4, i.e. hell
hw[^4..] //keep from "4 back from end" to end, i.e. orld
hw[..^4] //keep from start to "4 back from end", i.e. hello_w
hw[7..10] //keep between 7 and 10, i.e. orl
hw[4..^4] //keep between 4 from start and 4 from end, i.e. o_w
hw[^8..8] //keep between 8 from end and 8 from start, i.e. lo_wo
等等..
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400017.html
標籤:C#
