Calculating unique words in a string [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a page called post summary.
Under this page, I want to count the total number of words and total number of unique words.
I managed to count the total number of words in the post successfully.
However, I do not know how I can count the unique words.
Eg: "I enjoyed school today very much."
Expected output:
Total word count: 6
Unique word count: 5
Here is my current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace empTRUST
{
public partial class PostSummary : Form
{
string target_fbid;
string fbStatus;
public PostSummary(string target_fbid, string fbStatus)
{
InitializeComponent();
this.target_fbid = target_fbid;
this.fbStatus = fbStatus;
}
private void PostSummary_Load(object sender, EventArgs e)
{
label_totalwordcount.Text = fbStatus.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
}
}
}

I don't understand your example since there are no repeating words in "I enjoyed school today very much". However, this is a naive approach which might work for you:
var allWords = text.Split();
int count = allWords.Length; // 6
int unqiueCount = allWords.Distinct().Count(); // 6
It is naive because punctuation characters modify the result. So you might want to replace them in the first step:
var allWords = text.ToUpperInvariant().Replace(".", "").Replace(",","").Split(); // ...
Also, the case modifies the result, so you could compare case-insensitively if that is desired.

Can use something like this:
"I enjoyed school school today very much.".Split(' ').Distinct()
This one returns 6, even if there is "school" word that appears 2 times.
EDIT
if you need some custom comparison logic (say case insensitive) you may use Distinct overload where you can specify custom equality comparer.

The first tought is:
public int GetUniqueWordsCount(string input)
{
return input.Split(' ').GroupBy(s => s).Count();
}
If you would like a case insensitive solution you could add .ToLower() or .ToUpper() conversion to your group key selector. Also you may implement your own IEqualityComparer if you want some custom comparsion logic.

Related

How to check more than one value from dictionary in an if statement? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
Im just starting to learn unity and saw this task in one of my c# studying books. I have to create a code using an if statement inside foreach, so that it checks if i can afford each item in the dictionary, but i have no idea how to check all of them or even once specific, so i could write if 3 times for example.
At the moment my Log shows all the items and thier values, but shows if i can afford only the first one. What should i put in the IF brackets to check every value after it appears it Log?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LearningCurve : MonoBehaviour
{
public int currentGold = 3;
void Start()
{
Dictionary<string, int> itemInventory = new Dictionary<string, int>()
{
{"Potions", 4 },
{"Daggers", 3 },
{"Lockpicks", 1 }
};
foreach (KeyValuePair<string, int> itemCost in itemInventory)
{
Debug.LogFormat("Item {0} - {1}g", itemCost.Key, itemCost.Value);
if (currentGold >= itemCost.Value)
{
Debug.Log("I can afford that!");
}
}
}
I am not sure if I understood the question but I will try to give you a basic overview of what is happening in the code you posted.
Let's start with the if, how an if block works is simple you put a boolean bool for short in C# that can have two different values true and a false, inside the if(BOOL VALUE) and if the value is true it will run the code between the { CODE TO RUN }.
Let's refactor the code a bit to see what is going on here.
Dictionary<string, int> itemInventory = new Dictionary<string, int>()
{
{"Potions", 4 },
{"Daggers", 3 },
{"Lockpicks", 1 }
};
foreach (KeyValuePair<string, int> itemCost in itemInventory)
{
Debug.LogFormat("Item {0} - {1}g", itemCost.Key, itemCost.Value);
bool iCanBuyitem = currentGold >= itemCost.Value;
Debug.LogFormat("{0} >= {1} is {2}", currentGold, itemCost.Value,iCanBuyitem);
if (iCanBuyitem)
{
Debug.LogFormat("I can buy {0} ", itemCost.Key);
}else
{
Debug.LogFormat("I can't buy {0} ", itemCost.Key);
}
}
Unlike in mathematics in programing symbol >= is not an equality symbol but something called a binary operator that takes two variables of one of the many numeric types in c# in your dictionary they are integers Dictionary<string, int> and produce a bool value that tells you if one number is more or equal to a second number, it's a method that has something similar to the the following signature public bool FirstIsBiggerOrEqualToSecond(int first, int second)
Here is a dotnet fiddle demonstrating the output https://dotnetfiddle.net/oWlYlY
Read the question header You mean, if you want to put two or more conditions inside the IF, you have to use && operator:
if (currentGold >= itemCost.Value && currentGold <= 15)
{
Debug.Log("I have enough gold to buy this item and it's cheap.");
}
Testing the code snippet provided two logs within the Console: "I can afford that!". Through this, I have determined that the issue lies within your snippet implementation. I suggest you check if you have enabled Collapse within the Console.
I have attached an Imgur link for reference.
Console Log

How do I add 1 number to a array? [duplicate]

This question already has answers here:
Add new item in existing array in c#.net
(20 answers)
Closed 1 year ago.
I do not have anything other than the normal
using System;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
}
}
}
And I know that having nothing at the start and still asking questions isnt highly looked on but STILL...
Im trying to create a code that asks you for an integer, and if you answer anything over 0, it ADDS the given number to an array, once you stop giving numbers (example type some "stop") it prints out ALL the numbers given to the array.
I DO NOT need the full code for something like this, just an answer to how do I append to an array without making it insanely complicated (things ive found on the google are like 20 lines of code but im pretty sure its not that hard).
Sorry for the long post and in short, how do I append to an array? If you can provide me a code, please implement it in the C# code or give me a "explanation" how to do it. Thank you very much!
You probably don't want to use an array, you want a different data structure that allows easy expansion, like List<T>. For List<T>, you simply call .Add, like:
using System;
using System.Collections.Generic;
namespace TryStuff
{
class Program
{
static void Main(string[] args)
{
var myList = new List<int>();
while(int.TryParse(Console.ReadLine(), out int x))
{
if (x > 0)
{
myList.Add(x);
}
}
Console.WriteLine("You entered: " + string.Join(",", myList));
}
}
}
This should keep allowing you to enter integer numbers and add them to the list if the number is greater than 0. It ignores all numbers 0 or less than 0. If you type anything that is not a number, it will stop and print out the list you entered.

EndsWith() not working properly [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to add the corresponding index of all the strings in the tres4 array, if they match the end of the input string. Yet, my list gets filled with all the indexes 1-12, as opposed to only those, matching the end of my input string. Only 1 should be added to my List in this case.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Encoding
{
class Program
{
static void Main(string[] args)
{
string[] tres4 = {
"CHU",
"TEL",
"OFT",
"IVA",
"EMY",
"VNB",
"POQ",
"ERI",
"CAD",
"K-A",
"IIA",
"YLO",
"PLA"
};
string message = "CHUTEL";
List<int> digits = new List<int>();
for (int i = 0; i < tres4.Length; i++)
{
if (message.EndsWith(tres4[i]));
{
digits.Add(i);
}
}
Console.WriteLine(String.Join(", ", digits));
}
}
}
You have an extra semicolon:
if (message.EndsWith(tres4[i]));
See the semicolon at the end? Remove it and it'll work.
Next time you should give a debugger a try, it would show you the problem right away.
Remove ; from if condition
if (message.EndsWith(tres4[i]))

using List for first names [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am getting errors on my first names and other areas and I don't know if it is a basic logic error or my concept. In my PromptName() it seems to be not returing anything along with my Display(index, searchedName);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Seven
{
class Seven
{
static void Main(string[] args)
{
// IMPORTANT CODE REQUIREMENT: In the following list declaration,
// the order of the items in firstNames
// cannot be "manually" changed.
// ------------------------------------------------
List<string> firstNames = { "Johnny", "Alice", "Cory",
"Steve", "Dennis" };
// ------------------------------------------------
int index;
string searchedName = PromptName();
while (searchedName.Equals("end"))
{
index = firstNames.BinarySearch(serchedName);
Display(index, searchedName);
}
Console.Read();
}
private void Display(int index, string name)
{
Console.WriteLine();
if (index >= 0)
{
Console.WriteLine("Yes, {0} is in our course.", searchedName);
}
else
{
Console.WriteLine("No, {0} is not in our course.", name);
}
Console.Write("");
}
private string PromptName()
{
Console.Write("To terminate the program, enter 'end' for the student name.");
Console.Write("Enter the first name of the student to be searched in our course: ");
return Console.ReadLine();
}
}
}
Your while loop does not execute unless PromptName() does return "end".
Change
while (searchedName.Equals("end"))
to
while (!searchedName.Equals("end"))
You have an additional problem that you do not prompt for a new name again. Do that at the end of your while loop, right after your call to Display().
This is the type of problem that is easily resolved with a debugger. If you have not yet learned how to use one in your environment, I would suggest prioritizing it. The time you invest in learning to debug will quickly pay for itself.
UPDATE
I just noticed that your list is not declared properly. It should be
List<string> firstNames = new List<string>() { "Johnny", "Alice", "Cory",
"Steve", "Dennis" };
You may already know this, but on line 25 there is a typo:
Line 25: index = firstNames.BinarySearch(serchedName);
serchedName should be searchedName

richtextbox application test c# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm very new to c#. I created a forms. A richtextbox and a button in it.
I have a list of operators: Sum, Subtract,Multi,Div.I want to run a small richtextbox test. For example,in the richtextbox I write a text (eg. Sum(1,2)) and then click the button. A return result(eg.3) prints in the richtextbox.
My idea is to use string contains
foreach( var element in operatorlist)
{
string text=richtextbox.text;
if( text.contains(element)== true)
{
element(parameter1,parameter2);//something like this
}
}
I met two questions right row.
My first question is how to get the mathematical operation from the richtextbox text. Is there a better way than mine?
My second question is once we know the operator,how to allocate the two parameters in the richtextbox to the operator.
I'm not asking for coding, I'm just looking for ideas. If you have a good idea and wish to share.
You can evaluate an expression using the DataTable.Compute function:
int p1 = 1 ; string s1 = p1.ToString() ;
int p2 = 2 ; string s2 = p2.ToString() ;
int p3 = 3 ; string s3 = p3.ToString() ;
// Compute (p1+p2)*p3 ==> 9
int result = new DataTable().Compute( "("+s1+"+"+s2+")*"+s3+")","") ;
or directly:
string expression = "(1+2)*3" ;
int result = new DataTable().Compute(expression,"") ;
I think this comes down to personal style. Your way will definitely work, so good on you for that. The way I would do it is to create a Dictionary of strings to an enum. So for example, said dictionary and enum might look like this:
enum Operator { Addition = 0, Subtraction = 1, Multiplication = 2, Division = 3, etc};
var operatorDictionary = new Dictionary<string, Operator>()
{
{"Addition", Operator.Addition},
{"Subtraction", Operator.Subtraction},
etc...
};
Then to get the value you would just do
Operator operation;
operatorDictionary.TryGetValue(string operationString, out operation);
and you would have to then build some code that switches through the Operators and performs the correct operation. There is even a way of converting a string to an enum, so that would work as well.
It looks like the parameters are in a consistent format, so you would just make a simple method that splits by parenthesis and the comma, and returns the strings that it found.
Let me know if you need anything explained more.

Categories

Resources