Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
How to get the length of array means how much words in array?

For name fetching I used array for splitting variable, but when I put only first name then it gives error so I think first we get count of variable then match.
so please help me.

My code is:-
C#
String[] Spilted = Name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
      
            String firstname = Spilted[0];
            String lastname = Spilted[1];


            SqlCommand cmd = new SqlCommand("Select PROFILE_ID,FIRST_NAME,PROFILE_REQUEST_STATUS from DSProfile.HDR_PROFILE  where FIRST_NAME='" + firstname + "' and LAST_NAME='" + lastname + "'  and PROFILE_REQUEST_STATUS='" + false + "'", con);
            // SqlCommand cmd = new SqlCommand("Select p.PROFILE_ID,g.FRIEND_ID,p.FIRST_NAME,g.ACCEPT_STATUS from DSProfile.HDR_PROFILE p,DSMailBox.HDR_GROUP g where p.FIRST_NAME='" + friendname + "' and p.PROFILE_ID=g.FRIEND_ID and ACCEPT_STATUS='" + false + "'", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            int cnt = ds.Tables[0].Rows.Count;
            DT = ds.Tables[0];
            GridView1.DataSource = ds;
            GridView1.DataBind();
Posted
Updated 25-Nov-12 22:51pm
v2
Comments
Sergey Alexandrovich Kryukov 27-Nov-12 1:44am    
Are you sure words are always space-separated? How about some punctuation?
--SA

Use the Length[^] property:
C#
if( Spilted.Length == 1)
{
    // Code for first name only.
}
else
if( Spilted.Length == 2)
{
    // Code for first and last name.
}
 
Share this answer
 
try this
C#
String Name = "first last";
        String[] Spilted = Name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
        String firstName, lastName;
        if (Spilted.Length == 2)
        {
            firstName = Spilted[0];
            lastName = Spilted[1];
        }
        else if (Spilted.Length == 1)
            firstName = Spilted[0];
 
Share this answer
 
hi,

Try this also i think you want to count words in the whole string...


C#
int count = 0;
        string st = "this is your string including spaces and we are counting spaces count plus one is your words in the sentance ";
        foreach (char c in st.Trim())
        {
            if (char.IsSeparator(c))
            {
                count++;
            }
        }
        int totWords = count + 1;
        lblResult.Text = count.ToString();


i know it will helps you 100%
Thank you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900