C# 2.0 函数从字符串中获取第二个单词
我需要编写一个函数,它将返回第一个单词(第一个空格)之后的部分。
例如,我在 C# 2.0 中得到了以下字符串。
string str = "M000. New Delhi"
现在我想编写一个函数,如果传递了 str
则返回“New Delhi”。
请推荐!!
I need to write a function that will return me the part after the first word (first whitespace).
For example I have got below string in C# 2.0.
string str = "M000. New Delhi"
Now I want to write a function which return "New Delhi" if str
is passed.
Please suggest!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
获取第一个空格之后的字符串部分:
即使字符串中碰巧没有空格,这也会给出结果。在这种情况下,
IndexOf
方法将返回-1
,因此代码将返回整个字符串。如果在这种情况下您想要一个空字符串或异常,那么您将首先将索引获取到变量中,以便您可以检查该值:To get the part of the string after the first space:
This will also give a result even if there happens to be no space in the string. The
IndexOf
method will return-1
in that case, so the code will return the entire string. If you would want an empty string or an exception in that case, then you would get the index into a variable first so that you can check the value:无论传递什么字符串,这都有返回“New Delhi”的额外好处!
This has the added benefit of returning "New Delhi" no matter what string is passed!
干得好。
但最大的问题是“当它传递其他东西时,你希望它做什么?”
Here you go.
But the big question is "What do you want it to do when it is passed something else?"
第 3 步:获取给定字符串的起始索引为的子字符串
您在第 2 步中找到的数字(针对您的案例的 str.Substring(6))
您可以对任何字符串使用此方法来查找第一个空格之后的部分,这意味着第一个单词之后的部分。
Step 3: Take the substring of the given string with start index of
the number you found in Step 2 (str.Substring(6) for your case)
You can use this method for any string to find the part after the first whitespace, which means the part after the first word.
这一切都非常不清楚。最简单的情况:
更复杂的情况:
It's all very unclear. Simplest case:
More sophisticated:
// 替换“M000”。
// replace the "M000. "