2013-07-26 63 views
-1
using System; 
namespace MyCSharpLearning 
{ 
    class TrimMethod 
    { 
     public static void Main(string[] args) 
     { 
      string txt = Console.ReadLine(); 
      char[] SpaceRemove = { ' ' }; 
      txt = txt.Trim(SpaceRemove); 
      Console.WriteLine("Your result is: {0}", txt); 
      Console.ReadLine(); 
     } 
    } 
} 

不working..help !!!!!!空間從一個句子中移除,但不工作

+0

'Trim'將裁剪沒有參數的空格。 – Romoku

+0

我已經運行的代碼,它顯示爲[String.Trim]指定的工作(http://msdn.microsoft.com/en-us/library/system.string.trim.aspx)。也許您對其功能的期望與API不匹配? – user7116

+0

我不認爲人們應該downvote一個問題,因爲他們是新的/不明白庫。他們清楚地表明瞭努力,但誤解了修剪的工作原理。 – Gray

回答

2

您所呼叫的方法是String.Trim的空格,其作用:

從當前在陣列中指定一組字符 的所有前導和尾隨出現字符串對象。

使用String.Replace所有空間從代碼

txt = txt.Replace(" ", ""); 

使用正則表達式來刪除尾隨空格

txt = Regex.Replace(txt, "^[ \t\r\n]", ""); 

一個側面說明:

+0

非常感謝你 – Hossain

4
public static void Main(string[] args) 
{ 
    string txt = Console.ReadLine(); 
    txt = txt.Replace(" ",""); 
    Console.WriteLine("Your result is: {0}", txt); 
} 

看起來像你想要的。

0

string.Trim(params char [])將刪除僅在字符串開頭或結尾處傳遞的字符,而不是字符串中間的字符。

 string txt = Console.ReadLine(); 
     txt = txt.Replace(" ", ""); 
     Console.WriteLine("Your result is: {0}", txt); 
     Console.ReadLine(); 

string.Trim(params char[])

移除一組在從當前字符串對象的陣列中指定的字符 的所有前導和尾隨發生。

順便說一句,如果您只需要刪除字符串的開頭或結尾的空格,則不需要指定該字符數組。修剪()單獨去除所有其中whitespaces are defined here

+0

than than its great – Hossain