分割字符串以进行搜索操作 [英] split a string for search operation

查看:92
本文介绍了分割字符串以进行搜索操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI
我喜欢将用于搜索操作的字符串拆分为stringList

例如:
文本框输入
这是搜索我的"程序的我的字符串"

StringList元素
1.此
2.是
3.我的琴弦
4.对于
5.搜索我的
6.程序



为了将所有内容拆分成单独的单词,我可以使用

HI
i like to split a string for search operation to a stringList

e.g:
Textbox input
This is "my string" for "searching in my" program

StringList elements
1. This
2. is
3. my string
4. for
5. searching in my
6. program



For splitting all in separate words i can use

SearchString.Split(' ').ToList();


但是然后我没有将组合的搜索标签作为我的stringList中的一个条目

有人对我有解决办法吗?

谢谢


but then i don''t have the combined search tags as one entry in my stringList

does someone have a solution for me?

thanks

推荐答案

我的文章 ^ ].

为了测试此实用程序,我创建了一个预解析器的模拟器.NET使用该模拟器来解析您显示的命令行字符串.请参阅"6.命令行测试"一章并找到类SA.Universal.Utilities.CommandLineSimulationUtility(据我所能理解的那样)-您想要的是什么.

—SA
I have something similar in my article Enumeration-based Command Line Utility[^].

For testing of this utility, I created a simulator of the pre-parser .NET uses to parse command line strings the way you show. Please see the chapter "6. CommandLine Testing" and locate the class SA.Universal.Utilities.CommandLineSimulationUtility — it does — as far as I could understand you — what you want.

—SA


这可能不是最有效的方法,但这应该很接近您的需求:

This probably isn''t the most efficient way, but this should be pretty close to what you need:

public static ICollection<string> ConvertToStringList(string input)
{
	string[] split = input.Split(' ');

	List<string> stringList = new List<string>();

	bool inQuotes = false;
	StringBuilder sb = new StringBuilder();

	foreach (string s in split)
	{
		if (s.StartsWith("\""))
		{
			inQuotes = true;
			sb = new StringBuilder(s.Substring(1));
			sb.Append(" ");
		}
		else if (s.EndsWith("\""))
		{
			inQuotes = false;
			sb.Append(s.Substring(0, s.Length - 1));
			stringList.Add(sb.ToString());
		}
		else
		{
			if (inQuotes)
			{
				sb.Append(s);
				sb.Append(" ");
			}
			else
			{
				stringList.Add(s);
			}
		}
	}

	return stringList;
}


这可能与您获得的效果差不多.它使用正则表达式进行拆分: http://stackoverflow.com /questions/554013/regular-expression-to-split-on-spaces-un-in-quotes [
This is probably about as good as you will get. It uses regular expression to split: http://stackoverflow.com/questions/554013/regular-expression-to-split-on-spaces-unless-in-quotes[^]


这篇关于分割字符串以进行搜索操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆