C# 2.0 function to get Second Word from string [closed]
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!!
To get the part of the string after the first space:
string city = str.Substring(str.IndexOf(' ') + 1);
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:
string city;
int index = str.IndexOf(' ');
if (index == -1) {
throw new ArgumentException("Unable to find a space in the string.");
} else {
city = str.Substring(index + 1);
}
string WhichIsBestDelhi(String str)
{
return "New Delhi";
}
This has the added benefit of returning "New Delhi" no matter what string is passed!
string s = str.Split(new char[]{'.'})[1].Trim();
I want to write a function which return "New Delhi" if str is passed.
Here you go.
public string NewDehliFunction(string str)
{
if (str == "M000. New Delhi")
return "New Delhi";
else
return "?"; // what happens here???
}
But the big question is "What do you want it to do when it is passed something else?"
- Step 1: Take the first index of " "(whitespace) (5 for your string)
- Step 2: Increment the number you found in Step 1, by 1 (6 for your case)
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)
private static string ReturnThePartOfAStringAfterTheFirstWordAndWhiteSpace(string str) { if(str.Contains(" ")) { int indexOfFirstWhiteSpace = str.IndexOf(" "); string remainingStringAfterTheFirstWhiteSpace = str.Substring(indexOfFirstWhiteSpace + 1); return remainingStringAfterTheFirstWhiteSpace; } else return str; }
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:
var result = str.Substring(6);
More sophisticated:
var result = str.Substring(str.IndexOf(". ")); // Possible off-by-one; can never remember
// replace the "M000. "
str.Replace("M000. ",String.Empty);
精彩评论