Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在连字符之前拆分字符串-asp.net c#_C#_.net_Split - Fatal编程技术网

在连字符之前拆分字符串-asp.net c#

在连字符之前拆分字符串-asp.net c#,c#,.net,split,C#,.net,Split,我有一个字符串: 10989898 - test1 或者另一个例子: 123178239182 - test2 我需要这样的输出: 在第一种情况下: 10989898 在第二种情况下: 123178239182 表示连字符前的值。我如何才能做到这一点?您可以使用字符串拆分方法: string s = "10989898 - test1"; string str = s.Substring( 0, s.IndexOf( "-" ) ).Trim(); string[] splitStr

我有一个字符串:

10989898 - test1
或者另一个例子:

123178239182 - test2
我需要这样的输出:

在第一种情况下:

10989898 
在第二种情况下:

123178239182

表示连字符前的值。我如何才能做到这一点?

您可以使用字符串拆分方法:

string s = "10989898 - test1";
string str = s.Substring( 0, s.IndexOf( "-" ) ).Trim();
string[] splitString = string.split('-');

string requiredString = splitString[0];


需要修剪,否则结果的末尾仍有+1的空间用于记住修剪()。仅仅因为你看不到空间并不意味着它不在那里。这很糟糕,你无缘无故地创建了一个一次性数组
string result = theString.Substring(0, theString.IndexOf("-")).Trim();
<html>
<head>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {


        });
        function replaceFunc() {
            var s = document.getElementById("foo1").value;
            alert(s.replace(/[^0-9]/g, ""));
        }
    </script>
</head>
<body>
<input type="button" value="replace non-numeric" onclick="replaceFunc()" />
<input type="text" id="foo1"  />
</body>
</html>
Regex reg = new Regex("[^0-9]", RegexOptions.Singleline);
Console.WriteLine(Regex.Replace("123 -test 456", "[^0-9]", ""));