2013-12-19 41 views
-4

我有這個字符串:大家好,我是
我想從每個單詞中取出前兩名字符。結果是:Hetoal。我能怎麼做?我試圖用一個foreach以頭字符

foreach(string str in String)

,但我收到一個錯誤:不能char類型轉換爲字符串

+0

你的錯誤是因爲當你通過一個字符串枚舉,你'char'每個字符,而不是字符串。所以它應該是'foreach(字符串中的char c)'。但這可能不是你想要的。 –

回答

3

你需要的句子串分成的話,像這樣:

var sentence = "Hello to all."; 
var words = sentence.Split(' '); 

然後,您可以遍歷句子中的每個單詞並獲取每個單詞的前兩個字符,並將它們附加到結果中,如下所示:

string result; 
var resultBuilder = new StringBuilder(); 

foreach(string word in words) 
{ 
    // Get the first two characters if word has two characters 
    if (word.Length >= 2) 
    { 
     resultBuilder.Append(word.Substring(0, 2)); 
    } 
    else 
    { 
     // Append the whole word, because there are not two first characters to get 
     resultBuilder.Append(word); 
    } 
} 

result = resultBuilder.ToString(); 
+0

假定該字符串將包含2個字符。而不是「2」,你可以使用「Math.Min(2,word.Length)」。 – Paul

1

代碼例如:

string someString = "Hello to all"; 
string[] words = someString.Split(' '); 
string finalString = ""; 

foreach (string word in words) { 
    finalString += word.Substring(0, 2); 
} 
// finalString = "Hetoal"; 

此拆分串成單詞,然後的foreach字它找到的第2個字符和它們附加到finalString對象。

1

一個可能的解決方案可以

string str = "Hello to all.";  
StringBuilder output = new StringBuilder(); 
foreach (string s in str.Split(' ')) 
{ 
    output.Append(s.Take(2)); 
} 
string result = output.ToString(); 
0

你可以做到這一點

分割你的字符串周圍空間

string[] words = s.Split(' '); 
    foreach (string word in words) 
    { 
     Console.WriteLine(word.Substring(0,2)); 
    } 
0

一些LINQ這裏:

string s = "Hello to all"; 
var words = s.Split(' '); 
var result = new string(words.SelectMany(w=>w.Take(2)).ToArray()); 
0
 String str = "Hello to all"; 
     String[] words = str.Split(' '); 
     String completeWord = ""; 
     foreach (String word in words) 
     { 
      if(word.Length>1) 
      completeWord+=word.Substring(0, 2); 
     } 
0
string str = "Hello to all"; 
string result = str.Split().Select(word => word.Substring(0, 2)).Aggregate((aggr, next) => aggr + next); 
0
//original message 
string message = "hello to all"; 

//split into a string array using the space 
var messageParts = message.Split(' '); 

//The SelectMany here will select the first 2 characters of each 
// array item. The String.Join will then concat them with an empty string "" 
var result = String.Join("",messageParts.SelectMany(f=>f.Take(2))); 
+0

請解釋您的答案的技術細節。 – Notinlist

0
string word = "Hellow to all"; 
string result = ""; 
foreach(var item in word.Take(2)) 
{ 
    result += item; 
} 
+0

這導致「他」。 (甚至沒有編寫它的寫法) – germi

+0

字符串結果需要一個初始值; – SHM

1
string myString = "Hello to all"; 
var result = myString 
      .Split(' ') 
      .Select(x => x.Substring(0,Math.Min(x.Length,2))) 
      .Aggregate((y,z) => y + z);