[英]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.