How to count number of lines in a textbox in C# GUI - c#-4.0

I am using Visual Studio 2010 and want to count number of lines in a C# textbox. I have tried Textbox.Lines.Count but it is not working as "Lines" is no more available in 2010.Is there any alternate way?

Try use
var count = Textbox.Lines.Length;
More detail here
Or try this:
string[] tmpArray = textBox1.Lines;
int count = tmpArray.Length;

int first = 0;
int last = 0;
count=0;`enter code here`
last = textBox.GetLastVisibleLineIndex();
count++;
while (first <= last)
{
String dummy = textBox.GetLineText(first);
if (dummy.Contains("\n") || dummy.Contains("\r") || dummy.Contains("\r\n"))
{
dummy = dummy.TrimEnd('\r', '\n');
count++;
}
first++;
}

Related

How do I delete a word with Recursion and count the times it deletes?

I've completed about half of my assignment where I have to count the "chickens" in a string, remove the chickens, and return the amount of times I have to remove them.
public static int countChickens(String word)
{
int val = word.indexOf("chicken");
int count = 0;
if(val > -1){
count++;
word = word.substring(val + 1);
//I'm aware the following line doesn't work. It's my best guess.
//word.remove.indexOf("chicken");
val = word.indexOf("chicken");
}
return count;
}
As is, the program counts the correct amount of chickens in the word itself. (Sending it "afunchickenhaschickenfun" returns 2.) However, I need it to be able to return 2 if I send it something like "chichickencken" because it removed the first chicken, and then the second chicken came into play. How do I do the remove part?
Not tested and writen in sudo code, but should give you a better idea on a way to approach this.
int numberOfChickens = 0;
public void CountAndReplaceChicken(string word)
{
int initCheck = word.indexOf("chicken");
if (initCheck > -1)
{
word = word.remove.indexOf("chicken"); // not sure about the syntax in Eclipse but given you figure this part out
numberOfChickens++;
int recursionCheck = word.indexOf("chicken");
if (recursionCheck > -1)
CountAndReplaceChicken(word);
}
}
Okay, the teacher showed us how to do it a few days later. If I understood David Lee's code right, this is just a simplified way of what he did.
public static int countChickens(String word)
{
int val = word.indexOf("chicken");
if(val > -1){
return 1 + countChickens(word.substring(0, val) + word.substring(val + 7));
}
return 0;
}

I tried with String Split with Varying number of elements in each row of data. I am not able to trace NULL at the end

Trying to read from a data file with number of rows of data and each row the number of elements are varying.
StreamReader read = new StreamReader("TextFile1.txt");
string str1 = " ";
while (str1 != null)
{
str1 = read.ReadLine();
if (str1 != null)
{
richTextBox1.AppendText("\n"+str1);
string[] s = str1.Split(' ');
i = 0;
sum = 0;
while (s[i] != null)
{
if(i>0)
j=int.Parse(s[i]);
sum = sum + j;
i = i + 1;
}
}
}
Presuming the code you posted is C#, you should use the String.length property.
Just a snippet of that from the inside of your loop:
string[] s = str1.Split(' ');
i = 0;
sum = 0;
while (i < s.length)
{
j=int.Parse(s[i]);
sum = sum + j;
i = i + 1;
}
By the way, I removed the if(i > 0) condition as it seems rather unnecessary. However, if you would like to exclude the first element on the line (which is what the if(i>0) condition was doing), then simply change i = 0; to i = 1;.

String/Array in Java

Does this work? I'm trying to print a message in this.
char[] tempMessage = message.toCharArray();
String[] message2 = message.split(" ");
Integer.toString(number).toCharArray();
for(int x = 0; x<newMessage.length; x++)
{
}
Although its better to use a StringBuilder, I can show it using String(s).
String[] strArr = "hello world".split("\\s+");
String s = String.valueOf(strArr[0].charAt(0))+strArr[0].length()+String.valueOf(strArr[1].charAt(0))+strArr[1].length();
Output : h5w5
String[] message2 = message.split("\\s+");
String output = "";
for(int i = 0; i < message2.length; i++)
{
output += "" + message2[i].charAt(0) + message2[i].length();
}
//output has output string.
TheLostMind's solution is already good, but I think it needs a solution for Strings of arbitrary length.
String outputString = "";
for(String x : message.split("\\s+"))
{
outputString = outputString.concat(x.charAt(0) + x.length());
}
As stated in the comments, this solution is very similiar to brso05's solution. The difference is in using the :-Operator in the for-loop. It's shorter and IMHO easier to understand, as it says 'for each String in the resulting array'.
Also, using the concat()-function is considered safer in my work environment.

Count the number of frequency for different characters in a string

i am currently tried to create a small program were the user enter a string in a text area, clicks on a button and the program counts the frequency of different characters in the string and shows the result on another text area.
E.g. Step 1:- User enter:- aaabbbbbbcccdd
Step 2:- User click the button
Step 3:- a 3
b 6
c 3
d 1
This is what I've done so far....
public partial class Form1 : Form
{
Dictionary<string, int> dic = new Dictionary<string, int>();
string s = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
s = textBox1.Text;
int count = 0;
for (int i = 0; i < s.Length; i++ )
{
textBox2.Text = Convert.ToString(s[i]);
if (dic.Equals(s[i]))
{
count++;
}
else
{
dic.Add(Convert.ToString(s[i]), count++);
}
}
}
}
}
Any ideas or help how can I countinue because till now the program is giving a run time error when there are same charachter!!
Thank You
var lettersAndCounts = s.GroupBy(c=>c).Select(group => new {
Letter= group.Key,
Count = group.Count()
});
Instead of dic.Equals use dic.ContainsKey. However, i would use this little linq query:
Dictionary<string, int> dict = textBox1.Text
.GroupBy(c => c)
.ToDictionary(g => g.Key.ToString(), g => g.Count());
You are attempting to compare the entire dictionary to a string, that doesn't tell you if there is a key in the dictionary that corresponds to the string. As the dictionary never is equal to the string, your code will always think that it should add a new item even if one already exists, and that is the cause of the runtime error.
Use the ContainsKey method to check if the string exists as a key in the dictionary.
Instead of using a variable count, you would want to increase the numbers in the dictionary, and initialise new items with a count of one:
string key = s[i].ToString();
textBox2.Text = key;
if (dic.ContainsKey(key)) {
dic[key]++;
} else {
dic.Add(key, 1);
}
I'm going to suggest a different and somewhat simpler approach for doing this. Assuming you are using English strings, you can create an array with capacity = 26. Then depending on the character you encounter you would increment the appropriate index in the array. For example, if the character is 'a' increment count at index 0, if the character is 'b' increment the count at index 1, etc...
Your implementation will look something like this:
int count[] = new int [26] {0};
for(int i = 0; i < s.length; i++)
{
count[Char.ToLower(s[i]) - int('a')]++;
}
When this finishes you will have the number of 'a's in count[0] and the number of 'z's in count[25].

Convert Table to Text with Spaces

I've come across this several times in a couple years of programming so I decided to do some research to see if it was possible. Often I create data structures in code that are initialized in a table like manner, with rows and columns, and I would have liked to have this table-to-text feature for code readability. How can you create a table in word, or excel, or some other program, and output the cells of the table to text, with spaces (not tabs)? Word can do it with tabs, and excel can do it with misaligned spaces. Is there any program out there that automates this?
Have you tried using a monospace font, such as courier, when you export from excel? Most fonts will adjust spacing based on the specific width, height and kerning of each character but a monospace font will allow you to use spaces for alignment.
As for converting tabs to spaces automagically, there must be 100s if not 1000s of methods, apps, commands available out there.
I spent an hour or 2 researching this. I experimented with excel and word and they both came so close to exact solution that it made me crazy. I tried other programs online but with no luck. Here's my solution, Microsoft's Word's Table-To-Text feature and custom C# program that converts the Word-tabified text to column aligned text with spaces and not tabs.
1) Put your columns and rows in an MS Word Table
2) Convert table to text with tabs (look up how to do this)
3) Save the converted table to a plain text file
4) Use my program to open and convert the file
5) Copy the text in the output file to your code
Below is the C# Windows Form Application I wrote. I apologize for lack of optimization. I was at work and wanted it done as quickly as possible:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
OpenFileDialog of = new OpenFileDialog();
of.Title = "Select Tabbed Text File To Convert";
if (of.ShowDialog() != DialogResult.OK)
return;
StreamReader s = new StreamReader(of.OpenFile());
List<string> lines = new List<string>();
string line;
// Get each line into an array of lines.
while ((line = s .ReadLine()) != null)
lines.Add(line);
int numTabs = 0;
// count the number of tabs in each line, assume good input, i.e.
// all lines have equal number of tabs.
foreach (char c in lines[0])
if (c == '\t')
numTabs++;
for (int i = 0; i < numTabs; i++)
{
int tabIndex = 0;
// Loop through each line and find the "deepest" location of
// the first tab.
foreach (string l in lines)
{
int index = 0;
foreach (char c in l)
{
if (c == '\t')
{
if (index > tabIndex)
tabIndex = index;
break;
}
index++;
}
}
// We know where the deepest tab is, now we go through and
// add enough spaces to take the first tab of each line out
// to the deepest.
//foreach (string l in lines)
for (int l = 0; l < lines.Count; l++)
{
int index = 0;
foreach (char c in lines[l])
{
if (c == '\t')
{
int numSpaces = (tabIndex - index) + 1;
string spaces = "";
for (int j = 0; j < numSpaces; j++)
spaces = spaces + " ";
lines[l] = lines[l].Remove(index, 1);
lines[l] = lines[l].Insert(index, spaces);
break;
}
index++;
}
}
}
FileInfo f = new FileInfo(of.FileName);
string outputFile = f.FullName.Insert(f.FullName.IndexOf(f.Extension), " (Aligned)");
StreamWriter w = new StreamWriter(outputFile);
foreach (string l in lines)
w.Write(l + "\r\n");
w.Close();
s.Close();
MessageBox.Show("Created the file: " + outputFile);
}
}
}

Resources