在遇到空格后,我想丢弃字符串中的剩余字符(可以是任何字符).
例如.我希望字符串"10 1/2"变为"10";
目前我正在使用Split,但这似乎有点矫枉过正:
string TrimMe = "10 1/2";
string[] cleaned = TrimMe.Split(new char[] {' '});
return string[0];
Run Code Online (Sandbox Code Playgroud)
我觉得应该有一个更简单的方法.
Ahm*_*eed 12
其他一些选择:
string result = Regex.Match(TrimMe, "^[^ ]+").Value;
// or
string result = new string(TrimMe.TakeWhile(c => c != ' ').ToArray());
Run Code Online (Sandbox Code Playgroud)
但是,您开始使用的IMO更简单,更易于阅读.
编辑:两个解决方案将处理空字符串,如果没有找到空格则返回原始字符串,如果以空格开头则返回空字符串.
ang*_*son 11
这应该工作:
Int32 indexOfSpace = TrimMe.IndexOf(' ');
if (indexOfSpace == 0)
return String.Empty; // space was first character
else if (indexOfSpace > 0)
return TrimMe.Substring(0, indexOfSpace);
else
return TrimMe; // no space found
Run Code Online (Sandbox Code Playgroud)
类似于另一个答案,但更简洁:
int indexSpace = trimMe.IndexOf(" ");
return trimMe.Substring(0, indexSpace >= 0 ? indexSpace : trimMe.Length);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5761 次 |
| 最近记录: |