Clearing String/Text - string

Redirect me if this is already a previously solved issue!
In my program, I have a Stage in which the user can view a list of content, stored in a list consisting of Strings.
goToView.setOnAction(event ->{
menuStage.close();
viewStage.show();
String horseNameList = "";
for(int i = 0; i < accountList.size(); i++){
if(accountList.get(i).userName.equals(uName)){
for(int j = 0; j < accountList.get(i).createdHorses.size(); j++){
horseNameList += accountList.get(i).createdHorses.get(j);
horseNameList += "\n" + "\n";
}
}
Text hNameListTXT = new Text(horseNameList);
hNameListTXT.setFont(Font.font("Tahoma", FontWeight.NORMAL, 12));
listVbox.getChildren().add(hNameListTXT);
}
createdHorses is a List of Strings, listVbox is as you may think a VBox where the String (which converts to a Text) is printed. Now, when I close the Stage with the following EventHandler, nothing in particular happens:
backView.setOnAction(event -> {
viewStage.close();
menuStage.show();
});
But as I then open the Stage once again (by using another EventHandler similar to the one I use to close the first Stage with), my List (or String) har been doubled. What should I do to clear the String (or possibly the Text) so that it doesn't display it twice?

What should I do to clear the String (or possibly the Text) so that it
doesn't display it twice?
The VBox has a method getChildren() which returns an ObservableList. So you could use clear() on it to remove all the children.

Related

CComboBox FindString empty

The MFC CComboBox allows a person to do an AddString of an empty string. I just proved that by doing a GetCount() before and another after the AddString; Count was 0, then it became 1; and the GUI also seems to reflect it, as its list was an huge empty box, and when adding it became a one-liner.
I also proved it further by doing
int a = m_combo.GetCount();
CString sx= _T("Not empty string");
if(a == 1)
m_combo.GetLBText(0, sx);
TRACE(_T("Start<%s>End"), sx);
and the Output window displays
File.cpp(9) : atlTraceGeneral - Start<>End
so we conclude the sx variable is empty.
Then I do a FindString having a CString m_name variable which is empty:
int idx= m_combo.FindString(-1, m_name);
And it returns CB_ERR!
Is it standard behavior for empty string entries? Official documentation doesn't say anything about it!
If it is, what is the simplest way to override it? Is there some parameter or change in the resources to change the behaviour? If there is not, I am thinking about deriving or composing a class just for the case where the string is Empty!
I did it manually for the empty string and it works!
CString sItem;
int idx_aux= CB_ERR;
// need it because FindString, FindStringExact and SelectSring return CB_ERR when we provide an empty string to them!
if(m_name.IsEmpty())
{
for (int i=0; i<m_combo.GetCount(); i++)
{
m_combo.GetLBText(i, sItem);
if(sItem.IsEmpty())
{
idx_aux= i;
break;
}
}
}
else
idx_aux= m_combo.FindString(-1, m_name);

How to make the return false if the arraylist already have the string present in class?

I'm new to coding.
How do I return a false if there is a string being added that's already in the arraylist?
For example, if you have a list of dog names in the class and you add new dog names in the list, but don't add it when the same dog name was already in the list?
The Solution:
You could use a for statement to iterate through your array list:
public static bool checkArray(string dogName)
{
for int i=0; i<arrayName.Length; i++) // basic for loop to go through whole array
{
if (arrayName[i] == dogName) //checks if array value at index i is the dog's name
{
return true; //if it is, return true
}
}
return false; //gone through whole array, not found so return false
}
This means you can call your method via
string Name = "myDogsName";
bool isAlreadyPresent = checkArray(Name);
Note
This is written in C#, and so other coding languages will slightly
differ in their syntax.
isAlreadyPresent will then contain a bool value if the dog is
present or not
I have written this (for learning purposes) in (possibly) an
inefficient way, but should allow you to understand what is happening
at each stage.
the i++
The i++ may confuse new programmers, but effectively it is the same as writing
i = i + 1;
This also works for i--;
i = i - 1;
Or even i*=2;
i = i * 2;

Noob, creating string method's indexof and substring

As an assignment we are supposed to create methods that copy what string methods do. We are just learning methods and I understand them, but am having trouble getting it to work.
given:
private String st = "";
public void setString(String p){
st = p;
}
public String getString(){
return st;
}
I need to create public int indexOf(char index){}, and public String substring(int start, int end){} I've succesfuly made charAt, and equals but I need some help. We are only allowed to use String methods charAt(), and length(), and + operator. No arrays or anything more advanced either. This is how I'm guessing you start these methods:
public int indexOf(char index){
for(int i = 0; i < st.length(); i++){
return index;
}
return 0;
}
public String substring(int start, int end){
for(int i = 0; i < st.length(); i++){
}
return new String(st + start);
}
thanks!
here's my two working methods:
public boolean equals(String index){
for(int a = 0; a < index.length() && a < st.length(); a++){
if(index.charAt(a) == st.charAt(a) && index.length() == st.length()){
return true;
}
else{
return false;
}
}
return false;
}
public char charAt(int index){
if(index >= 0 && index <= st.length() - 1)
return st.charAt(index);
else
return 0;
}
For your indexOf method, you're on the right track. You'll want to modify the code in the loop. Since you're looping through the whole String, and you only have two methods available, which will help you most to get the characters from the String? Look to your other methods (equals and charAt) to see how you did them, it might give a hint. Remember, you want find a single character in your String and print out the index in which you found it.
For your substring method what you need to do is get all the characters that are represented beginning at start index and go up until end index. A loop is a good start, but you will need a base String to hold your progress in (you will need an empty String). The beginning and end point of your loop need a looking at. For substring, you want to get everything starting at start and everything before end. For instance, if I do the following:
String myString = "Racecar";
String sub = myString.substring(1, 4);
System.out.println(sub);
I should get the output ace.
I would give you the answer, but I think helping guide your reasoning will give you more benefit. Enjoy your assignment!

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