从字符串创建string [] args。 [英] Creating string[] args from a string.
问题描述
我有一个类,它在构造函数中接受程序主函数中的字符串[] args。我希望能够使用字符串创建实例。
你可能知道,它比仅仅拆分空格要复杂一点,因为空间是有效的当前面和后面跟着s。是否有一种简单的方法可以对此进行逆向工程,我没有想到?
< pre lang =c#> static void Main( string [] args)
{
if (args.length == 0 )
{
string databasestatement = GetArgsFromDatabase();
string [] argsfromDB = DOSOMETHING(databasestatement);
myclass fromDB = new myclass(argsfromDB);
}
else
{
myclass fromArgs = new myclass(args);
}
}
Daniel Earwicker有一个非常好的实现 StackOverflow [ ^ ]:
public static string TrimMatchingQuotes( this string 输入, char 引用)
{
if ((输入.Length > = 2 )&&
(输入[ 0 ] == quote)&&(输入[input.Length - 1 ] == quote))
return input.Substring( 1 ,input.Length - 2 );
return 输入;
}
public static IEnumerable< string>拆分(此 字符串 str,Func< char,bool>控制器)
{
int nextPiece = 0 ;
for ( int c = 0 ; c < str.Length; c ++)
{
if (controller(str [c]))
{
yield return str.Substring(nextPiece,c - nextPiece);
nextPiece = c + 1 ;
}
}
yield return str。子(nextPiece);
}
public static IEnumerable< string> SplitCommandLine( string commandLine)
{
bool inQuotes = 假跨度>;
return commandLine.Split(c = >
{
if (c == ' \ ')inQuotes =!inQuotes;
return !inQuotes&& c == ' ';
})
。选择(arg = > arg.Trim()。TrimMatchingQuotes(' \'))
。 Where(arg = > !string.IsNullOrEmpty(arg));
}
同一个帖子还包括 P / Invoke解决方案 [ ^ ]
I have a class that accepts the string[] args from the program's main function in its constructor. I would like to be able to create instances using a string as well.
As you may know, it's a little more complicated than just splitting on spaces since space's are valid when preceded and followed by "s. Is there a simple way to reverse engineer this that I'm not thinking of?
static void Main(string[] args)
{
if (args.length == 0)
{
string databasestatement = GetArgsFromDatabase();
string[] argsfromDB = DOSOMETHING(databasestatement);
myclass fromDB = new myclass(argsfromDB);
}
else
{
myclass fromArgs = new myclass(args);
}
}
There's a pretty good implementation by Daniel Earwicker on StackOverflow[^]:
public static string TrimMatchingQuotes(this string input, char quote) { if ((input.Length >= 2) && (input[0] == quote) && (input[input.Length - 1] == quote)) return input.Substring(1, input.Length - 2); return input; } public static IEnumerable<string> Split(this string str, Func<char, bool> controller) { int nextPiece = 0; for (int c = 0; c < str.Length; c++) { if (controller(str[c])) { yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; } } yield return str.Substring(nextPiece); } public static IEnumerable<string> SplitCommandLine(string commandLine) { bool inQuotes = false; return commandLine.Split(c => { if (c == '\"') inQuotes = !inQuotes; return !inQuotes && c == ' '; }) .Select(arg => arg.Trim().TrimMatchingQuotes('\"')) .Where(arg => !string.IsNullOrEmpty(arg)); }
The same thread also includes the P/Invoke solution[^].
这篇关于从字符串创建string [] args。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!