简体   繁体   English

C#如果字符串包含

[英]C# If string contains

I'm working in C# and I have 2 textboxes. 我正在使用C#,并且有2个文本框。 If the user enters text in the first box and presses a button the text copy's into text box 2. I've now made another text box and I'm wanting it to show all the strings that contain @ if the user has entered them. 如果用户在第一个框中输入文本,然后按一下按钮,则文本副本将进入文本框2。现在,我创建了另一个文本框,如果用户输入了它们,我希望它显示所有包含@的字符串。
For example, 例如,
User enters "Hi there @joey, i'm with @Kat and @Max" 用户输入“嗨,@ joey,我和@Kat和@Max在一起”
Presses button 按下按钮
"Hi there @joey, i'm with @Kat and @Max" appears in textbox 2 “嗨,@ joey,我和@Kat和@Max在一起”出现在文本框2中
and @joey @Kat @Max appear in text box 3. @joey @Kat @Max出现在文本框3中。

Just not sure how i'd do the last part. 只是不确定我将如何做最后一部分。
Any help thanks! 任何帮助谢谢! ............................................................................................. Okay, so I decided to go of and try to learn how to do this, I've got this so far ................................................... ...........................................好吧,所以我决定去并尝试学习如何做到这一点,到目前为止

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

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

This works however it prints all the words after the word with the @ symbol. 此方法有效,但是会在带有@符号的单词之后打印所有单词。 So like if I was to enter "Hi there @joey what you doing with @kat" it would print @joey what you doing with @kat instead of just @joey and @kat. 因此,如果我要输入“嗨,@ joey您对@kat的操作”,它将打印@joey您对@kat的操作,而不仅仅是@joey和@kat。

我将字符串拆分成一个数组然后使用string.contains获取包含@符号的项目。

A simple RegEx to find words that begin with @ should be sufficient: 一个简单的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
}

You could use regular expressions to find the words you search for. 您可以使用正则表达式查找要搜索的单词。

Try this regex 试试这个正则表达式

@\w+

Maybe not the neatest soultion. 也许不是最整洁的灵魂。 But something like this: 但是这样的事情:

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()
            ));

A Regex would work well here : 正则表达式在这里可以很好地工作:

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