簡體   English   中英

C#如果字符串包含

[英]C# If string contains

我正在使用C#,並且有2個文本框。 如果用戶在第一個框中輸入文本,然后按一下按鈕,則文本副本將進入文本框2。現在,我創建了另一個文本框,如果用戶輸入了它們,我希望它顯示所有包含@的字符串。
例如,
用戶輸入“嗨,@ joey,我和@Kat和@Max在一起”
按下按鈕
“嗨,@ joey,我和@Kat和@Max在一起”出現在文本框2中
@joey @Kat @Max出現在文本框3中。

只是不確定我將如何做最后一部分。
任何幫助謝謝! ................................................... ...........................................好吧,所以我決定去並嘗試學習如何做到這一點,到目前為止

string s = inputBx.Text;
             int i = s.IndexOf('@');

            string f = s.Substring(i);
            usernameBx.Text = (f);

此方法有效,但是會在帶有@符號的單詞之后打印所有單詞。 因此,如果我要輸入“嗨,@ joey您對@kat的操作”,它將打印@joey您對@kat的操作,而不僅僅是@joey和@kat。

我將字符串拆分成一個數組然后使用string.contains獲取包含@符號的項目。

一個簡單的RegEx來查找以@開頭的單詞就足夠了:

string myString = "Hi there @joey, i'm with @Kat and @Max";
MatchCollection myWords = Regex.Matches(myString, @"\B@\w+");
List<string> myNames = new List<string>();

foreach(Match match in myWords) {
    myNames.add(match.Value);
}
var indexOfRequiredText = this.textBox.Text.IndexOf("@");

if(indexOfRequiredText > -1)
{
    // It contains the text you want
}

您可以使用正則表達式查找要搜索的單詞。

試試這個正則表達式

@\w+

也許不是最整潔的靈魂。 但是這樣的事情:

string str="Hi there @joey, i'm with @Kat and @Max";
var outout= string.Join(" ", str
               .Split(' ')
               .Where (s =>s.StartsWith("@"))
               .Select (s =>s.Replace(',',' ').Trim()
            ));

正則表達式在這里可以很好地工作:

var names = Regex.Matches ( "Hi there @joey, i'm with @Kat and @Max", @"@\w+" );

foreach ( Match name in names )
    textBox3.Text += name.Value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM