Hi I need to find longest sequence of words in text that's matching condition: if word is ending with letter N other word should start with letter N. N - could be any letter. For Example:
Simple Elephant
Apple Strong
So first line is matching my mentioned condition so I need to print it out to console.
Failing to think of an algorithm how this should work.
I make this code for you. Can answer to your questions.
List<string> sentenses = new List<string>();
sentenses.Add("hi, my name is Sam.");
sentenses.Add("Hi,is,settled,drums.");
sentenses.Add("Add all your sentenses here");
string longestSentense ="";
int longestCount = 0;
foreach(string sentense in sentenses)
{
string[] words = Regex.Split(sentense, "[^a-zA-Z]"); // cut sentense by all not letter character
int count = 0;
for (int i=0;i<words.Length-1;i++)
{
// check if last letter of words[i] is the same letter as the first or words[i+1]
if(words[i].Equals("") || words[i+1].Equals("")) continue; // don't look to "empty word"
if (words[i][words[i].Length-1].Equals(words[i + 1][0])) count++;
}
// if here is the biggest number of matching words, we save it
if(count>longestCount)
{
longestCount = count;
longestSentense = sentense;
}
}
Console.WriteLine("The sentence that contains the most of matching words : \n"
+ longestSentense + "\n"
+ " with " + longestCount + " junctions between matching words.");
Console.ReadKey();
Related
This is my code. How can I edit it to show every word which is at the odd position ONLY to be reversed?
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == ' ')
{
result = tmp + " " + result;
tmp = "";
}
else
tmp += input[i];
}
result = tmp + " " + result;
Console.WriteLine(result);
Example input:
"How are you today"
to output:
"How era you yadot"
Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
You can achieve it with the help of LINQ:
var input = "hello this is a test message";
var inputWords = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join(" ",
inputWords.Select((w, i) =>
i % 2 == 0
? w
: new string(w.Reverse().ToArray())
));
Where w in the select is the word, and i is the index, starting at 0 for the first word. % is the modulus operator and gets the remainder. If i % 2 == 0 (i.e. i can be divided by 2 with no remainder), then the original is returned. If there is a remainder (odd) then the reversed word is returned. Finally, it's all wrapped up in a string.Join(" ", items); which turns it back into a normal string rather than an array of items.
Try it online
So far you have a string, like this:
string input = "I want to reverse all odd words (odd words only!).";
And you, naturally, want to perform the task. Now it's the main question what's an odd word?
If you mean word's position (I at position 0, want at 1 - should be reversed etc.)
then you can use regular expressions to match words and Linq to process them:
using System.Linq; // To reverse single word
using System.Text.RegularExpressions; // To match the words within the text
...
// Let's elaborate the test example: add
// 1. some punctuation - ()!. - to preserve it
// 2. different white spaces (spaces and tabulation - \t)
// to add difficulties for naive algorithms
// 3. double spaces (after "to") to mislead split based algorithms
string input = "I want to reverse all\todd words (odd words only!).";
int index = 0; // words' indexes start from zero
string result = Regex.Replace(
input,
"[A-Za-z']+", // word is letters and apostrophes
match => index++ % 2 == 0
? match.Value // Even words intact
: string.Concat(match.Value.Reverse())); // Odd words reversed
Console.WriteLine(result);
If you want to reverse the words with odd Length, i.e. I, all, odd then all you have to do is to change the condition to
match => match.Value % 2 == 0
Outcome:
I tnaw to esrever all ddo words (ddo words ylno!).
Please, notice, that the punctuation has been preserved (only words are reversed).
OP: Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
public static void Main()
{
string input = "How are you today Laken-C";
//As pointed out by #Dmitry Bychenko string input = "How are you today";
//(double space after How) leads to How are uoy today outcome
input = Regex.Replace(input, #"\s+", " ");
var inp = input.Split(' ').ToList();
for (int j = 0; j < inp.Count(); j++)
{
if(j % 2 == 1)
{
Console.Write(inp[j].Reverse().ToArray());
Console.Write(" ");
}
else
Console.Write(inp[j] + " ");
}
}
OUTPUT:
DEMO:
dotNetFiddle
try this is perfect working code..
static void Main(string[] args)
{
string orgstr = "my name is sagar";
string revstr = "";
foreach (var word in orgstr.Split(' '))
{
string temp = "";
foreach (var ch in word.ToCharArray())
{
temp = ch + temp;
}
revstr = revstr + temp + " ";
}
Console.Write(revstr);
Console.ReadKey();
}
Output: ym eman si ragas
Sorry, It's kinda hard to explain it for me.
I want to get the index of the last new line character which placed before a different character in a C# application.
for example, I want the index of the \n which is placed before Hi
"\n\n\n\n\nHi\n\n\n"
Also I want the first index of \n which is placed after Hi.
I know String.LastIndexOf has multiple ways to use. I just don't know if I can or how to use it to get what I want.
EDIT
This is what I've came up to so far.
int firstIndex=myString.IndexOf("\n")==0 ? 0 : -1;
int secondIndex=myString.Text.Trim().IndexOf("\n");
I want to know if there's a better or more standard way to do that.
You can use the Regex.Matches to find the item with pattern. A simple approach can be
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var input = "\n\nHi\n\n\nTest\nTest";
var matches = Regex.Matches(input, "\\n");
for (int index = 0; index < matches.Count - 1; index++)
{
var match = matches[index];
if (match.Index + 1 != matches[index + 1].Index)
{
Console.WriteLine("Last Match found at " + match.Index);
Console.WriteLine("Next first Match found after last item at " + matches[index + 1].Index);
}
}
Console.WriteLine("Last Match found at " + matches[matches.Count - 1].Index);
}
}
It print the output as
Last Match found at 1
Next first Match found after last item at 4
Last Match found at 6
Next first Match found after last item at 11
Last Match found at 11
There lots of ways to skin this cat. Here's one
string input = "\n\n\n\n\nHi\n\n\n";
string [] split = input.Split('\n');
int prevN = -1, nextN = -1;
for (int i = 0; i < split.Length; i++) {
if (!String.IsNullOrEmpty(split[i])) {
prevN = i - 1;
nextN = i + split[i].Length;
break;
}
}
Console.WriteLine(prevN + "-" + nextN);
Prints "4-7". Is that correct?
You can try something like below
static void Main(string[] args)
{
int index = "\n\n\n\n\nHi\n\n\n".IndexOf("hi", StringComparison.OrdinalIgnoreCase);
Console.WriteLine("\n\n\n\n\nHi\n\n\n".Split('i')[1].IndexOf("\n") + index);
Console.WriteLine("\n\n\n\n\nHi\n\n\n".Split('i')[1].LastIndexOf("\n") + index);
}
I am working on a Homework problem and just need some assistance in this one area. I am not asking for you to do my homework for me, just need some help, as I cannot find any additional information on the web.
I have created an Overload method that takes a string array as its parameter. I believe I created the method correctly to allow me to let a user enter in multiple strings that would be stored into an array.
I am now working in the static void main and am having trouble thinking of the code that needs to be implemented to allow the user to enter in multiple strings, until the user inputs 'q' on its own line, in which it will show the user how many words they had just entered.
please see the code below. you will be able to see the overload method and the part that I am stuck on in the static void main, which is enclosed with asterisks.
Again, I am not asking you do my hw, I just need some assistance with this one part. Also, here is an example of what I need the program to do. thank you in advanced for your help.
Enter several sentences, when done entering sentences, use q by itself on the last line.
Hello, how are you?
I'm fine, and you?
Just fine, just fine.
q
There are 12 words in that text.
Enter several sentences, when done entering sentences, use q by itself on the last line.
q
static void Main(string[] args)
{
Console.WriteLine("Main Menu");
Console.WriteLine("Choose from the following:");
Console.WriteLine("1. Word Count" + "\n" + "2. Vowel Counting" + "\n" + "3. Exit");
Console.Write("Enter your selection: ");
int s1 = Convert.ToInt32(Console.ReadLine());
if(s1 == 1)
{
Break:;
Console.WriteLine("Word Counter Menu");
Console.WriteLine("Choose from the following");
Console.WriteLine("1. Count the word in one sentence" + "\n" +
"2. Count the word in a paragraph" + "\n" +
"3. Parent Menu");
Console.Write("Enter your selection ");
int s2 = Convert.ToInt32(Console.ReadLine());
if(s2 == 1)
{
string sent1;
while (true)
{
Console.Write("Enter a sentence (q to quit, d for default): ");
sent1 = Console.ReadLine();
Console.WriteLine("There are " + Def1(sent1) + " words in the sentence: " + sent1);
if(sent1 == "d")
{
sent1 = "Hello";
Console.WriteLine("There are " + Def1(sent1) + " words in the sentence: " + sent1);
}
if(sent1 == "q")
{
goto Break;
}
}
}
**if (s2 == 2)
{
string sent2;
Console.WriteLine("Enter several sentences, when done entering" +
" sentences, use q by itself on the last line:");
while(true)
{
sent2 = Console.ReadLine();
if(sent2 == "q")
{
// Console.WriteLine("There are " + + " words in that text");
break;**
}
}
}
}
}
static int Def1(string d1 = "Hello")
{
int countWords = 0;
for (int i = 1; i < d1.Length; i++)
{
if (char.IsWhiteSpace(d1[i - 1]) == true)
{
if (char.IsLetterOrDigit(d1[i]) == true ||
char.IsPunctuation(d1[i]))
{
countWords++;
}
}
}
if (d1.Length > 2)
{
countWords++;
}
return countWords;
}
static int Def1(string[] d1)
{
var e = from a in d1 select a;
int cnt1 = e.Count();
return cnt1;
}
static int vow1(string v1)
{
char[] vowels = new char[] { 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U' };
int total = 0;
for(int i = 0; i < v1.Length; i++)
{
if(vowels.Contains(v1[i]))
{
total++;
}
}
return total;
For counting number of words in several strings (paragraph) you can write the code like this
if (s2 == 2) //2. Count the word in a paragraph
{
string senttence2;
List<string> sentences = new List<string>();
Console.WriteLine("Enter several sentences, when done entering" +
" sentences, use q by itself on the last line:");
senttence2 = Console.ReadLine();
while (senttence2 != "q")
{
sentences.Add(senttence2);
senttence2 = Console.ReadLine();
}
Console.WriteLine("There are " + GetWordCount(sentences) + " words in that text");
}
And this is the method (using Linq)
static int GetWordCount(IEnumerable<string> sentences)
{
return sentences.Select(s => s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Count()).Sum();
}
First of all your loop can be something like this.
You need two variables. first one is temporary value that holds the user input. its value is compared against q inside while loop. until the temporary value is not equal to q we should continue looping and append value of temp to another string which must hold all the inputs (except last q).
if (s2 == 2)
{
string temp = "";
Console.WriteLine("Enter several sentences, when done entering" +
" sentences, use q by itself on the last line:");
string finalString = ""; // initial empty value
while((temp = Console.ReadLine()) != "q") // assign input to temp and check its value
{
finalString += " " + temp; // temp was not `q` so append it to text.
}
Console.WriteLine(???); // explained later
}
Note that we added extra space for each appending temp to finalstring to make sure that words are separated at the end of line and start of next line.
What should be in Console.WriteLine(???);.
This can be done easily with Split method. You can Split the finalstring by spaces and commas. and then check if it contains words or not.
var possibleWords = finalString.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries)
RemoveEmptyEntries is just the option to remove empty items from result of split.
Now you have to check that each of these string items contains letters or not. if they contain letters we count it as word.
var letterCount = possibleWords.Count(x => x.Any(char.IsLetter));
The method Count counts when ever the x => x.Any(char.IsLetter) returns true.
x.Any(char.IsLetter) will return true when ever the string x contains at least one letter.
So you can print something like this.
Console.WriteLine("There are " + letterCount + " words in that text");
The better way to count letters would be to use Regexes but thats higher level than yours so i prefer not to put it here. Hope it helps.
How can I search for a word within a string ?
I have one text box which the user insert a string and another on with with text just some random text.
Are there any alterative ways of doing this besides using regex and IndexOf? Like using a for loop and checking the length and character in the word.
This is what I tried so far
int i = 0;
int count = 0;
input2.Trim();
while ((i = input2.IndexOf(input1, i)) != -1)
{
i = i + input1.Length;
count++;
}
MessageBox.Show(count.ToString() + " Matches Found");
Looks like you want to get the Count of search string in the text. You can try the following.
string searchString = "TEST";
string completeText = "Some sentence TEST with other words incluing TEST";
int count = completeText.Split(new string[]{"TEST"},StringSplitOptions.None)
.Count() - 1;
MessageBox.Show(count.ToString() + " Matches Found");
Use a regex to match the number of occurances,
string test = "THE DOG WENT TO TOWN DOG";
int j = Regex.Matches(test, "DOG").Cast<Match>().Count();
I have a code in C# and have to print a label with the name of the seller, but i have a problem.
Every line in the label comport 20 letters and i have 2 lines to put this name.
I need to arrange the name of the seller in the 2 lines, without cut words.
For example - Name: JOSE MAURICIO BERTOLOTO MENDES
Line1: JOSE MAURICIO
Line2: BERTOLOTO MENDES
someone know how i do this?
Thanks
EDIT: Based in the answers, i implemente this code:
string[] SellerPrint = Seller.Split(' ');
Line1 = "";
Line2 = "";
foreach (string name in SellerPrint )
{
if (Line1.Length <= 20)
{
if ((Line1 + name).Length <= 20)
Line1 += (Line1.Length == 0) ? name : " " + name;
else
break;
}
}
Line2 = (Seller.Replace(Line1, "").Length <= 20) ? Seller.Replace(Line1+ " ", "") : Seller.Replace(Line1+ " ", "").Remove(20);
Thanks for the help!
You could simply split the string into words using string.Split() and then add to each as long it small enough to add to the line.
I also wouldn't use the character count but use Graphics.MeasureString() instead.
You can split the full name in to it's individual parts.
var names = fullname.Split(' ');
Which will give you a string[]. From there you can do the math by looking at length of each string.
The idea is that you want to append all parts of the name until you will reach or exceed your 20 character limit on the next token. When that happens, append a new line with that token and continue appending until you hit the character limit once again.
Here is a quick example:
public static string FormatName(string name)
{
const int MaxLength = 20;
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (name.Length <= MaxLength)
return name;
string[] tokens = name.Split(' ');
if (tokens.Length == 0)
return name; //hyphen the name?
StringBuilder sb = new StringBuilder(name.Length);
int len = 0;
foreach (string token in tokens)
{
if (token.Length + len < MaxLength)
{
sb.Append(token + " ");
len += token.Length;
}
else
{
sb.Append(Environment.NewLine + token + " ");
len = 0;
}
}
return sb.ToString();
}
Note: I left the case open for when a section of the name, without spaces, is longer than 20 characters. Also, this example will continue on to the Nth line, if the name won't fit onto two lines.
Here is the logic.
Use String.split to split the name into an array. Iterate over the strings in the array, concat them into a line, while the line is less than 20 characters. A recursive function would be a good idea! When you are greater than two lines, drop the rest of the names that put it over.
I'm not sure but I think you can use a special character: '\n' (without the quotes)
Its basiclly stands for new line. So for example : JOSE MAURICIO BERTOLOTO MENDES will become JOSE MAURICIO \n BERTOLOTO MENDES.