[英]Remove a specific character from string
我有一個申請
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
有沒有辦法在我的代碼中添加一些東西以使其工作?
您可以使用Replace()
方法並將其替換為空字符串:
string wordWithoutLetter = word.Replace(letter, "");
Console.WriteLine(wordWithoutLetter);
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, ie o_world hw[..4] //keep from start to index 4, ie hell hw[^4..] //keep from "4 back from end" to end, ie orld hw[..^4] //keep from start to "4 back from end", ie hello_w hw[7..10] //keep between 7 and 10, ie orl hw[4..^4] //keep between 4 from start and 4 from end, ie o_w hw[^8..8] //keep between 8 from end and 8 from start, ie lo_wo
等等..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.