Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I wont to take string "My name is rohit"
and Count No of Spaces in String.
and wont user gives a iedex and print a word after a that space.

===============================

Ex.
Enter String .
My name is rohit

Enter Index no.
2

Your Search is...... " is"

=============================
Plz Any can Help me .......
or Suggest me what can i do....?
and How to do....?

Thnx in advance.........

What I have tried:

class Program
{
static void Main()
{
string[] w = SplitWords("rohit vijay batho nagpur");
foreach (string s in w)
{
Console.WriteLine(s);
}

// Console.WriteLine("Enter Index No.");
// w = Console.ReadLine();

Console.ReadLine();
}

/// <summary>
/// Take all the words in the input string and separate them.
///
static string[] SplitWords(string s)
{
//
// Split on all non-word characters.
// ... Returns an array of all the words.
//
return Regex.Split(s, @"\W+");


// @ special verbatim string syntax
// \W+ one or more non-word characters together
}
}
Posted
Updated 15-Feb-17 18:46pm

1. Split the string into array of words by space, [^]
2. The number of space will be the count of this array minus one, [^]
3. To get the item at index number i in the array, simply myArray[i], [^]
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 16-Feb-17 1:24am    
5
Peter Leow 16-Feb-17 2:21am    
Thank you, Karthik.
Try Below code:-

C#
string inputString = "My name is rohit";
string[] wordArray = inputString.Split(null); //split the string by whitespace.

//count the no. of whitespace
int countOfSpace = wordArray.Length -1;

int index = 2;
string newString = inputString.Substring(index);
string wordAfterIndex = newString.Split(null)[1]; //specify the index as to which word you want from the array.
 
Share this answer
 
Comments
Member 13004167 18-Feb-17 5:00am    
what can i do when user enters a -ve number as input or special Char(@,#,$,%,*etc)
for accessing the index NO......?

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