2011-01-25 11 views

risposta

15
string result = theString.Substring(0, theString.IndexOf("-")).Trim(); 
+4

+1 per ricordare a Trim(). Solo perché non puoi vedere quello spazio non significa che non sia lì. – JeffK

3
string s = "10989898 - test1"; 
string str = s.Substring(0, s.IndexOf("-")).Trim(); 
+0

Richiede un ritaglio o il risultato avrà ancora lo spazio alla fine – Manatherin

+0

@Manatherin: 10x –

4

È possibile utilizzare il metodo String Split:

string[] splitString = string.split('-'); 

string requiredString = splitString[0]; 
+3

Questo è un problema, la creazione di un array a perdere per nessun motivo – Manatherin

0

http://jsfiddle.net/98Snm/2/

<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> 

Aggiornamento

Regex reg = new Regex("[^0-9]", RegexOptions.Singleline); 
Console.WriteLine(Regex.Replace("123 -test 456", "[^0-9]", "")); 
Problemi correlati