I want to print the string in reverse format in for loop:
Input: I'm Learning c#
Output: c# Learning I'm
No Split functions and reverse functions should be used, it has to do only with forloop.
for (int i = m.Length - 1; i >= 0; i--)
{
b[j]=a[i];
j++;
if(a[i]==' '|| a[i]==0)
{
for (int x = b.Length - 1; x >= 0; x--)
{
c[k] = b[x];
Console.Write(c[k]);
k++;
}
}
} Console.ReadKey();
You have to create an array of the words in the sentence:
var words = input.Split(' ');
Then you just loop through the above array from the end to the start:
for(int i=words.Length-1; i>=0; i--)
{
Console.Write(words[i]+" ");
}
With LINQ and string methods you can simplify it:
var reversedWords = input.Split().Reverse(); // Split without parameters will use space, tab and new-line characters as delimiter
string output = string.Join(" ", reversedWords); // build reversed words, space is delimiter
Use Stack<Queue<char>>
Hey if you want to show off your knowledge of data structures, use a queue and a stack! This makes for a very concise answer as well.
You want the sentence to be LIFO with respect to words but FIFO with respect to letters within words, so you need a stack (which are LIFO) of queues (which are FIFO). You can take advantage of the fact that a string, a queue<char>, and a stack<char> all expose IEnumerable<char> as well, so it's easy to convert back and forth; once you have all the characters ordered in your data structure, you can extract the whole thing as a character array using SelectMany(), which you can pass to a string constructor for the final answer.
This solution uses no Split() or Reverse() functions, as required.
public static string ReverseSentence(string input)
{
var word = new Queue<char>();
var sentence = new Stack<IEnumerable<char>>( new [] { word } );
foreach ( char c in input )
{
if (c == ' ')
{
sentence.Push( " " );
sentence.Push( word = new Queue<char>() );
}
else
{
word.Enqueue(c);
}
}
return new string( sentence.SelectMany( w => w ).ToArray() );
}
Usage:
public void Test()
{
var input = "I'm Learning c#";
var output = ReverseSentence(input);
Console.WriteLine(output);
}
Output:
c# Learning I'm
DotNetFiddle
Without split and reverse, I modify your logic little bit to achieve what you need
namespace MyNamespace
{
public class Program
{
public static void Main(string[] args)
{
var m="this is mystring";
var b = new char [m.Length];
var j=0;
//Your code goes here
for (int i = m.Length - 1; i >= 0; i--)
{
b[j]=m[i];
j++;
if(m[i]==' ' || i==0)
{
if(i==0)
{
b[j]=' ';
}
for (int x = b.Length - 1; x >= 0; x--)
{
Console.Write(b[x]);
}
b=new char[m.Length];
j=0;
}
}
Console.ReadKey();
Console.WriteLine("Hello, world!");
}
}
}
Input: "this is mystring"
Output: "mystring is this"
Here is a simple console application for your question
Without using Reverse and Split methods (just for loop)
class Program
{
static void Main()
{
string input = "I'm learning C#";
string[] result = new string[3];
int arrayIndex = 0;
string tempStr = "";
// Split string
for (int i = 0; i < input.Length; i++)
{
tempStr += input[i].ToString();
if (input[i] != ' ')
{
result[arrayIndex] = tempStr;
}
else
{
tempStr = "";
arrayIndex++;
}
}
// Display Result
for (int i = result.Length - 1; i >= 0; i--)
{
System.Console.Write(result[i] + ' ');
}
System.Console.WriteLine();
}
}
Press Ctrl + F5 to run the program
Output: C# learning I'm
Related
I have tried this:
using System;
using System.Collections;
using System.Collections.Generic;
public class HelloWorld
{
public static string reverseWords(string str){
ArrayList strArr = new ArrayList();
int start = 0;
string revStr = "";
for(int i = 0; i < str.Length; i++){
if(str[i] == ' '){ // if there's a space,
while(start <= str[i - 1]){ // loop thru the iterated values before space
strArr.Add(str[start]); // add them to the ArrayList
start++; // increment `start` until all iterated values are-
} // stored and also for the next word to loop thru
}
}
for(int j = strArr.Count - 1; j >= 0; j--){
revStr += strArr[j] + " "; // keep appending ArrayList values to the-
} // string from the last to the first value
return revStr;
}
public static void Main(string[] args)
{
Console.WriteLine(reverseWords("Our favorite color is Pink"));
//Expected output : Pink is color favorite Our
}
}
And it's giving this error:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
Please help me understand why this is not working. And also, if there's better way to do this ReverseWord function manually(not using any built-in functions at all).
I'm sorry if this is such a noob question. Any constructive criticism is appreciated. Thanks!
Here is a little improved version of your code that actually works for what you are willing to do.
using System;
using System.Collections;
public class HelloWorld
{
public static string reverseWords(string str){
ArrayList strArr = new ArrayList();
string currentWordString = string.Empty;
string revStr = string.Empty;
for(int i = 0; i < str.Length; i++){
if(str[i] == ' '){ // if there's a space,
strArr.Add(currentWordString); // add the accumulated word to the array
currentWordString = string.Empty; // reset accumulator to be used in next iteration
}else {
currentWordString += str[i]; // accumulate the word
}
}
strArr.Add(currentWordString); // add last word to the array
for(int j = strArr.Count - 1; j >= 0; j--){
revStr += strArr[j] + " "; // keep appending ArrayList values to the-
} // string from the last to the first value
return revStr;
}
public static void Main(string[] args)
{
Console.WriteLine(reverseWords("Our favorite color is Pink"));
//Expected output : Pink is color favorite Our
}
}
I'll let you do the remaining. Like removing the trainling space at the end of the sentence. add seperators other than space (e.g comma, semicolons...)
Try this
"Our favorite color is Pink".Split('\u0020').Reverse().ToList().ForEach(x =>
{
Console.WriteLine(x);
});
This will help
public static string ReverseCharacters(string str)
{
if(str == null)
{
throw new ArgumentNullException(nameof(str));
}
int lastIndex = str.Length - 1;
char[] chars = new char[str.Length];
char temp;
for(int i = 0; i < str.Length/2+1; i++)
{
// Swap. You could refactor this to its own method if needed
temp = str[i];
chars[i] = str[lastIndex - i];
chars[lastIndex - i] = temp;
}
return new string(chars);
}
public static string ReverseWords(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
string space = " ";
StringBuilder reversed = new StringBuilder();
// reverse every characters
var reversedCharacters = ReverseCharacters(str);
// split words (space being word separator here)
var reversedWords = reversedCharacters.Split(space);
// for every revered word characters, reverse it back one more time and append.
foreach(var reversedWord in reversedWords)
{
reversed.Append(ReverseCharacters(reversedWord)).Append(space);
}
// remove last extra space
reversed = reversed.Remove(reversed.Length - 1, 1);
return reversed.ToString();
}
Here is the test result:
I'm doing an exercise that says I have to enter a phrase and put it in array, then I have to delete all the repeated characters and show the new phrase.
I did it like this but I don't know how to get char from string array and put it into another string array.
PS: I must only use the basics of C# and arrays :(
namespace Exercice3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Entrez une phrase SVP!!");
string phrase = Console.ReadLine();
string[] phraseArray = new string[]{ phrase };
string[] newPhrase = new string[phrase.Length];
for (int i = 0; i <= phrase.Length - 1; i++)
{
for (int j = 1; j <= phrase.Length - 1; j++)
{
if (phraseArray[i] != phraseArray[j])
newPhrase = phraseArray[i]; //Probleme here
}
}
Console.WriteLine(newPhrase);
}
}
}
something like this would do it. You don't have to do it this way...
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var newColl = new List<char>();
foreach(char c in "aaabbbccc".ToCharArray())
{
if (!newColl.Contains(c))
newColl.Add(c);
}
Console.WriteLine(new string(newColl.ToArray()));
}
}
Output:
abc
Array-only method
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const string orig = "aaabbbcccddd";
int origLen = orig.Length;
char[] newArr = new char[origLen]; // get max possible spots in arr
int newCount = 0;
for(int i = 0; i < origLen; i++)
{
bool yes = false;
for(int j = 0; j < newCount + 1; j++)
{
if (newArr[j] == orig[i])
{
yes = true;
break;
}
}
if (!yes)
{
newArr[newCount] = orig[i];
newCount++;
}
}
Console.WriteLine(new string(newArr));
}
}
Output:
abcd
The main problem here is that you are using arrays of strings. That is inappropriate because you are trying to iterate the characters of the string.
You need to construct your array of characters like this:
char[] phraseArray = phrase.ToCharArray();
This should allow you the ability to iterate the set of characters, check for duplicates, and form the new character array.
The reason why you're getting an IndexOutOfRangeException is because if you look at the two arrays:
string[] phraseArray = new string[]{ phrase };
And
string[] newPhrase = new string[phrase.Length];
The length of both arrays are completely different, phraseArray has a length of 1 and newPhrase will be set to the length of your phrase, so if you insert a world of more than 1 character both arrays will not match and then either:
if (phraseArray[i] != phraseArray[j])
Or
newPhrase = phraseArray[i];
Will fail, specially newPhrase = phraseArray[i];, because here you're trying to replace newPhrase an array, for a character phrase[i]. Basically your solution won't work. So what you can do is do what #Travis suggested, basically change your arrays from String[]to char[], then:
char[] phraseArray = phrase.ToCharArray();
Or Instead of using arrays you can just use another string to filter your phrase. The first string being your phrase and the second would be the string you'd add your non repeated characters to. basically this:
Console.WriteLine("Entrez une phrase SVP!!");
string phrase = Console.ReadLine();
string newPhrase = "";
// loop through each character in phrase
for (int i = 0; i < phrase.Length; i++) {
// We check if the character of phrease is within our newPhrase, if it isn't we add it, otherwise do nothing
if (newPhrase.IndexOf(phrase[i]) == -1)
newPhrase += phrase[i]; // here we add it to newPhrase
}
Console.WriteLine(newPhrase);
Don't forget to read the comments in the code.
Edit:
Based on the comments and suggestions given I implemented a similar solution:
Console.WriteLine("Entrez une phrase SVP!!");
char[] phrase = Console.ReadLine().ToCharArray();
char[] newPhrase = new char[phrase.Length];
int index = 0;
// loop through each character in phrase
for (int i = 0; i < phrase.Length; i++) {
// We check if the character of phrease is within our newPhrase, if it isn't we add it, otherwise do nothing
if (Array.IndexOf(newPhrase, phrase[i]) == -1)
newPhrase[index++] = phrase[i]; // here we add it to newPhrase
}
Console.WriteLine(newPhrase);
There is an interview question that asks me to attach every last letter of the word with the next word in C#. For example the input is "Hey hello world" and the output should be "He yhell oworld".
I've come up with the code below but is there a better way to do this? Perhaps in LINQ?
string inputString = "Hey Hello World";
string[] stringArray = inputString.Split(' ').ToArray();
StringBuilder resultString = new StringBuilder("");
StringBuilder lastLetter = new StringBuilder("");
for (int i = 0; i < stringArray.Length; i++)
{
string temp = stringArray[i].ToString();
if (i < stringArray.Length - 2)
{
resultString.Append(lastLetter + temp.Substring(0, temp.Length - 1));
lastLetter.Clear();
lastLetter.Append(" " + temp.Substring(temp.Length - 1, 1));
}
else
resultString.Append(lastLetter + temp.Substring(0, temp.Length));
}
Console.WriteLine(resultString);
How about using regex
var newtext = Regex.Replace("Hey hello world", #"(.) "," $1");
You are unnecessarily complicating the code. Simply replace space with previous character.
var input = "Hey Hello world";
var arr = input.Trim().ToCharArray();
for(int i =0; i< arr.Length; i++)
{
if(arr[i]==' ')
{
var temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}
Console.WriteLine(arr);
Here's a LINQ solution, since that seems to be what the OP is looking for.
using System;
using System.Linq;
public class Program
{
const char space = ' ';
public static string DoHomework(string input)
{
return new string
(
input.Select( (c,i) =>
{
if (i == 0 || i == input.Length-1) return c;
if (c == space) return input[i-1];
if (input[i+1] == space) return space;
return c;
}).ToArray()
);
}
public static void Main()
{
var input = "Hey hello world";
var output = DoHomework(input);
Console.WriteLine(output);
}
}
Output:
He yhell oworld
Try it out on DotNetFiddle
I'm working on reversing a sentence. I'm able to do it. But I'm not sure, how to reverse the word without changing the special characters positions. I'm using regex but as soon as it finds the special characters it's stopping the reversal of the word.
Following is the code:
Console.WriteLine("Enter:");
string w = Console.ReadLine();
string rw = String.Empty;
String[] arr = w.Split(' ');
var regexItem = new Regex("^[a-zA-Z0-9]*$");
StringBuilder appendString = new StringBuilder();
for (int i = 0; i < arr.Length; i++)
{
char[] chararray = arr[i].ToCharArray();
for (int j = chararray.Length - 1; j >= 0; j--)
{
if (regexItem.IsMatch(rw))
{
rw = appendString.Append(chararray[j]).ToString();
}
}
sb.Append(' ');
}
Console.WriteLine(rw);
Console.ReadLine();
Example : Input
Marshall! Hello.
Expected output
llahsram! olleh.
A basic solution with regex and LINQ. Try it online.
public static void Main()
{
Console.WriteLine("Marshall! Hello.");
Console.WriteLine(Reverse("Marshall! Hello."));
}
public static string Reverse(string source)
{
// we split by groups to keep delimiters
var parts = Regex.Split(source, #"([^a-zA-Z0-9])");
// if we got a group of valid characters
var results = parts.Select(x => x.All(char.IsLetterOrDigit)
// we reverse it
? new string(x.Reverse().ToArray())
// or we keep the delimiters as it
: x);
// then we concat all of them
return string.Concat(results);
}
The same solution without LINQ. Try it online.
public static void Main()
{
Console.WriteLine("Marshall! Hello.");
Console.WriteLine(Reverse("Marshall! Hello."));
}
public static bool IsLettersOrDigits(string s)
{
foreach (var c in s)
{
if (!char.IsLetterOrDigit(c))
{
return false;
}
}
return true;
}
public static string Reverse(char[] s)
{
Array.Reverse(s);
return new string(s);
}
public static string Reverse(string source)
{
var parts = Regex.Split(source, #"([^a-zA-Z0-9])");
var results = new List<string>();
foreach(var x in parts)
{
results.Add(IsLettersOrDigits(x)
? Reverse(x.ToCharArray())
: x);
}
return string.Concat(results);
}
This is a solution without LINQ. I wasn't sure about what are considered special characters.
string sentence = "Marshall! Hello.";
List<string> words = sentence.Split(' ').ToList();
List<string> reversedWords = new List<string>();
foreach (string word in words)
{
char[] arr = new char[word.Length];
for( int i=0; i<word.Length; i++)
{
if(!Char.IsLetterOrDigit((word[i])))
{
for ( int x=0; x< i; x++)
{
arr[x] = arr[x + 1];
}
arr[i] = word[i];
}
else
{
arr[word.Length - 1 - i] = word[i];
}
}
reversedWords.Add(new string(arr));
}
string reversedSentence = string.Join(" ", reversedWords);
Console.WriteLine(reversedSentence);
And this is the output:
Updated Output = llahsraM! olleH.
Here is a non-regex version that does what you want:
var sentence = "Hello, john!";
var parts = sentence.Split(' ');
var reversed = new StringBuilder();
var charPositions = sentence.Select((c, idx) => new { Char = c, Index = idx })
.Where(_ => !char.IsLetterOrDigit(_.Char));
for (int i = 0; i < parts.Length; i++)
{
var chars = parts[i].ToCharArray();
for (int j = chars.Length - 1; j >= 0; j--)
{
if (char.IsLetterOrDigit(chars[j]))
{
reversed.Append(chars[j]);
}
}
}
foreach (var ch in charPositions)
{
reversed.Insert(ch.Index, ch.Char);
}
// olleH, nhoj!
Console.WriteLine(reversed.ToString());
Basically the trick is to remember the position of special (i.e. non letter or digit) characters and insert them at the end to those positions.
This solution is without LINQ and Regex. It may not be an efficient answer but working properly for small string values.
// This will reverse the string and special characters will just stay there.
public string ReverseString(string rString)
{
StringBuilder ss = new StringBuilder(rString);
int y = 0;
// The idea is to swap values. Like swapping first value with last one. It will keep swapping unless it reaches at the middle of the string where no swapping will be needed.
// This first loop is to detect first values.
for(int i=rString.Length-1;i>=0;i--)
{
// This condition is to check if the values is String or not. If it is not string then it is considered as special character which will just stay there at same old position.
if(Char.IsLetter(Convert.ToChar(rString.Substring(i,1))))
{
// This is second loop which is starting from end to swap values from end with first.
for (int k = y; k < rString.Length; k++)
{
// Again checking last values if values are string or not.
if (Char.IsLetter(Convert.ToChar(rString.Substring(k, 1))))
{
// This is swapping. So st1 is First value in that string
// st2 is the last item in that string
char st1 = Convert.ToChar(rString.Substring(k, 1));
char st2 = Convert.ToChar(rString.Substring(i, 1));
//This is swapping. So last item will go to first position and first item will go to last position, To make sure string is reversed.
// Remember when the string value is Special Character, swapping will move forward without swapping.
ss[rString.IndexOf(rString.Substring(i, 1))] = st1;
ss[rString.IndexOf(rString.Substring(k, 1))] = st2;
y++;
// When the swapping is done for first 2 items. The loop will stop to change the values.
break;
}
else
{
// This is just increment if value was Special character.
y++;
}
}
}
}
return ss.ToString();
}
Thanks!
I'm trying to count the number of words from a rich textbox in C# the code that I have below only works if it is a single line. How do I do this without relying on regex or any other special functions.
string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";
foreach(string av in split_text)
{
if (av == "")
{
space_count++;
}
else
{
new_text = new_text + av + ",";
}
}
new_text = new_text.TrimEnd(',');
split_text = new_text.Split(',');
MessageBox.Show(split_text.Length.ToString ());
char[] delimiters = new char[] {' ', '\r', '\n' };
whole_text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries).Length;
Since you are only interested in word count, and you don't care about individual words, String.Split could be avoided. String.Split is handy, but it unnecessarily generates a (potentially) large number of String objects, which in turn creates an unnecessary burden on the garbage collector. For each word in your text, a new String object needs to be instantiated, and then soon collected since you are not using it.
For a homework assignment, this may not matter, but if your text box contents change often and you do this calculation inside an event handler, it may be wiser to simply iterate through characters manually. If you really want to use String.Split, then go for a simpler version like Yonix recommended.
Otherwise, use an algorithm similar to this:
int wordCount = 0, index = 0;
// skip whitespace until first word
while (index < text.Length && char.IsWhiteSpace(text[index]))
index++;
while (index < text.Length)
{
// check if current char is part of a word
while (index < text.Length && !char.IsWhiteSpace(text[index]))
index++;
wordCount++;
// skip whitespace until next word
while (index < text.Length && char.IsWhiteSpace(text[index]))
index++;
}
This code should work better with cases where you have multiple spaces between each word, you can test the code online.
There are some better ways to do this, but in keeping with what you've got, try the following:
string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
// new line split here
string[] lines = trimmed_text.Split(Environment.NewLine.ToCharArray());
// don't need this here now...
//string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";
Now make two foreach loops. One for each line and one for counting words within the lines.
foreach (string line in lines)
{
// Modify the inner foreach to do the split on ' ' here
// instead of split_text
foreach (string av in line.Split(' '))
{
if (av == "")
{
space_count++;
}
else
{
new_text = new_text + av + ",";
}
}
}
new_text = new_text.TrimEnd(',');
// use lines here instead of split_text
lines = new_text.Split(',');
MessageBox.Show(lines.Length.ToString());
}
This was a phone screening interview question that I just took (by a large company located in CA who sells all kinds of devices that starts with a letter "i"), and I think I franked... after I got offline, I wrote this. I wish I were able to do it during interview..
static void Main(string[] args)
{
Debug.Assert(CountWords("Hello world") == 2);
Debug.Assert(CountWords(" Hello world") == 2);
Debug.Assert(CountWords("Hello world ") == 2);
Debug.Assert(CountWords("Hello world") == 2);
}
public static int CountWords(string test)
{
int count = 0;
bool wasInWord = false;
bool inWord = false;
for (int i = 0; i < test.Length; i++)
{
if (inWord)
{
wasInWord = true;
}
if (Char.IsWhiteSpace(test[i]))
{
if (wasInWord)
{
count++;
wasInWord = false;
}
inWord = false;
}
else
{
inWord = true;
}
}
// Check to see if we got out with seeing a word
if (wasInWord)
{
count++;
}
return count;
}
Have a look at the Lines property mentioned in #Jay Riggs comment, along with this overload of String.Split to make the code much simpler. Then the simplest approach would be to loop over each line in the Lines property, call String.Split on it, and add the length of the array it returns to a running count.
EDIT: Also, is there any reason you're using a RichTextBox instead of a TextBox with Multiline set to True?
I use an extension method for grabbing word count in a string. Do note, however, that double spaces will mess the count up.
public static int CountWords(this string line)
{
var wordCount = 0;
for (var i = 0; i < line.Length; i++)
if (line[i] == ' ' || i == line.Length - 1)
wordCount++;
return wordCount;
}
}
Your approach is on the right path. I would do something like, passing the text property of richTextBox1 into the method. This however won't be accurate if your rich textbox is formatting HTML, so you'll need to strip out any HTML tags prior to running the word count:
public static int CountWords(string s)
{
int c = 0;
for (int i = 1; i < s.Length; i++)
{
if (char.IsWhiteSpace(s[i - 1]) == true)
{
if (char.IsLetterOrDigit(s[i]) == true ||
char.IsPunctuation(s[i]))
{
c++;
}
}
}
if (s.Length > 2)
{
c++;
}
return c;
}
We used an adapted form of Yoshi's answer, where we fixed the bug where it would not count the last word in a string if there was no white-space after it:
public static int CountWords(string test)
{
int count = 0;
bool inWord = false;
foreach (char t in test)
{
if (char.IsWhiteSpace(t))
{
inWord = false;
}
else
{
if (!inWord) count++;
inWord = true;
}
}
return count;
}
using System.Collections;
using System;
class Program{
public static void Main(string[] args){
//Enter the value of n
int n = Convert.ToInt32(Console.ReadLine());
string[] s = new string[n];
ArrayList arr = new ArrayList();
//enter the elements
for(int i=0;i<n;i++){
s[i] = Console.ReadLine();
}
string str = "";
//Filter out duplicate values and store in arr
foreach(string i in s){
if(str.Contains(i)){
}else{
arr.Add(i);
}
str += i;
}
//Count the string with arr and s variables
foreach(string i in arr){
int count = 0;
foreach(string j in s){
if(i.Equals(j)){
count++;
}
}
Console.WriteLine(i+" - "+count);
}
}
}
int wordCount = 0;
bool previousLetterWasWhiteSpace = false;
foreach (char letter in keyword)
{
if (char.IsWhiteSpace(letter))
{
previousLetterWasWhiteSpace = true;
}
else
{
if (previousLetterWasWhiteSpace)
{
previousLetterWasWhiteSpace = false;
wordCount++;
}
}
}
public static int WordCount(string str)
{
int num=0;
bool wasInaWord=true;;
if (string.IsNullOrEmpty(str))
{
return num;
}
for (int i=0;i< str.Length;i++)
{
if (i!=0)
{
if (str[i]==' ' && str[i-1]!=' ')
{
num++;
wasInaWord=false;
}
}
if (str[i]!=' ')
{
wasInaWord=true;
}
}
if (wasInaWord)
{
num++;
}
return num;
}
class Program
{
static void Main(string[] args)
{
string str;
int i, wrd, l;
StringBuilder sb = new StringBuilder();
Console.Write("\n\nCount the total number of words in a string
:\n");
Console.Write("---------------------------------------------------
---\n");
Console.Write("Input the string : ");
str = Console.ReadLine();
l = 0;
wrd = 1;
foreach (var a in str)
{
sb.Append(a);
if (str[l] == ' ' || str[l] == '\n' || str[l] == '\t')
{
wrd++;
}
l++;
}
Console.WriteLine(sb.Replace(' ', '\n'));
Console.Write("Total number of words in the string is : {0}\n",
wrd);
Console.ReadLine();
}
This should work
input.Split(' ').ToList().Count;
This can show you the number of words in a line
string line = Console.ReadLine();
string[] word = line.Split(' ');
Console.WriteLine("Words " + word.Length);
You can also do it in this way!! Add this method to your extension methods.
public static int WordsCount(this string str)
{
return Regex.Matches(str, #"((\w+(\s?)))").Count;
}
And call it like this.
string someString = "Let me show how I do it!";
int wc = someString.WordsCount();