2009-10-20 101 views
0

即時通訊在我的代碼在C#中有麻煩。我想分割沒有固定值的字符串。這裏'我的代碼請幫我解決這個問題。如何拆分多個字符串

protected void GridViewArchives_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     DataRowView drView = (DataRowView)e.Row.DataItem; 
     Literal litAuthors = (Literal)e.Row.FindControl("ltAuthors"); 

     string authors = drView["Author(s)"].ToString(); 
     //authors = Trent Riggs:[email protected]|Joel Lemke:[email protected] 
     string[] splitauthors = authors.ToString().Split("|".ToCharArray()); 


     foreach (string authornames in splitauthors) 
     { 
      litAuthors.Text = string.Format("{0}<br /><br />", authornames); 
     } 
    } 
} 

問題IM面對這裏是當我呈現頁面它只顯示一個字符串值,並且不顯示在陣列中的隨後的字符串。

用「|」分割字符串後, delimeter我想用名稱和電子郵件地址與分隔符「:」分割字符串。我該怎麼做呢?

回答

0
foreach (string authornames in splitauthors) 
     { 
      litAuthors.Text = string.Format("{0}<br /><br />", authornames); 
     } 

請檢查litAuthors.Text = string.Format("{0}<br /><br />", authornames); 裏面的for循環。 ü應使用

litAuthors.Text += string.Format("{0}<br /><br />", authornames); 
1

litAuthors.Text + =的String.Format( 「{0}

」,authornames);

2

你可以使用的,而不是你的foreach循環的String.Join方法:

string authors = drView["Author(s)"].ToString(); 
string[] splitAuthors = authors.Split('|'); 

litAuthors.Text = string.Join("<br /><br />", splitAuthors) + "<br /><br />"; 

編輯

我只注意到你的問題的第二部分 - 分離出作者姓名和電子郵件地址。你可以回去使用foreach環路,做這樣的事情:與 分割字符串後

string authors = drView["Author(s)"].ToString(); 
string[] splitAuthors = authors.Split('|'); 

StringBuilder sb = new StringBuilder(); 
foreach (string author in splitAuthors) 
{ 
    string[] authorParts = author.Split(':'); 

    sb.Append("Name=").Append(authorParts[0]); 
    sb.Append(", "); 
    sb.Append("Email=").Append(authorParts[1]); 
    sb.Append("<br /><br />"); 
} 
litAuthors.Text = sb.ToString();   
0

「|」 delimeter我想分割 字符串與名稱和電子郵件地址 與分隔符「:」。我該怎麼辦 這個?

你的意思是?

foreach (string authornames in splitauthors)   
{    
string[] authorDetails = authornames.Split(':'); 
litAuthors.Text += string.Format("{0}<br /><br />", authorDetails[0]);   
} 
0

就像這樣。

string authors = drView["Author(s)"].ToString(); 
//authors = Trent Riggs:[email protected]|Joel Lemke:[email protected] 
string[] splitauthors = authors.ToString().Split("|".ToCharArray()); 


foreach (string author in splitauthors) 
{ 
    string[] emailNameSplit = author.Split(":".ToCharArray()); 
    litAuthors.Text += string.Format("Name: {0} Email: {1}<br /><br />", emailNameSplit[0], emailNameSplit[1]); 
}