C# 相当于 C sscanf
可能的重复:
.NET 中是否有与“sscanf()”等效的函数?
sscanf 是从字符串读取格式良好的输入的好方法。
这个C#如何实现。
例如,
int a,b;
char *str= "10 12";
sscanf(str,"%d %d",&a,&b);
上面的代码将 10 分配给 a,12 分配给 b。
如何使用 C# 实现同样的效果?
Possible Duplicate:
Is there an equivalent to 'sscanf()' in .NET?
sscanf in C is a nice way to read well formatted input from a string.
How to achieve this C#.
For example,
int a,b;
char *str= "10 12";
sscanf(str,"%d %d",&a,&b);
The above code will assign 10 to a and 12 to b.
How to achieve the same using C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我写这篇文章只是为了消磨时间。
I'm just writing to kill time.
如果您不介意编写一些低级代码,那么用 C# 编写您自己的
sscanf()
方法并不困难。您可以在文章 A sscanf() Replacement for .NET 中查看我的版本。
Writing your own
sscanf()
method in C# isn't that difficult, if you don't mind writing a little low-level code.You can see my version in the article A sscanf() Replacement for .NET.
来自运行时例程和 .NET Framework 等效项
所以,我想没有直接的等价物。
from Run-Time Routines and .NET Framework Equivalents
So, I guess there's no direct equivalent.
C# 中没有直接的等效项。给定 C# 中的相同任务,您可以执行如下操作:
根据您可以假设输入的格式良好程度,您可能需要添加一些错误检查。
There is no direct equivalent in C#. Given the same task in C#, you could do it something like this:
Depending on how well-formed you can assume the input to be, you might want to add some error checks.
.NET Framework 中没有与
sscanf
直接等效的函数。实现相同功能的最简单方法是拆分字符串 (
String.Split< /code>
),然后使用
Int32.Parse 将后续部分分配给变量
方法。例如:框架中的许多不同数据类型都有
Parse
方法,包括枚举,如果您要从字符串中读取的值不一定是整数值。您还可以使用正则表达式,但对于如此简单的任务来说它们可能有点大材小用像这样。
编辑:如果您真的死心塌地使用
sscanf
,您始终可以考虑从 C 运行时库中 P/调用该函数。也许是这样的(未经测试):There is no direct equivalent of
sscanf
in the .NET Framework.The simplest way to achieve the same functionality is splitting the string (
String.Split
) and then assigning the subsequent parts to variables with theInt32.Parse
method. For example:Many different data types in the Framework have
Parse
methods, including enumerations, if the values you want to read in from the string are not necessarily integer values.You could also use regular expressions, but they're probably a bit overkill for a task as simple as this.
EDIT: If you're truly deadset on using
sscanf
, you could always consider P/Invoking the function from the C runtime libraries. Something like this perhaps (untested):