How to split value in asp.net? - c#

I Have a input value like
["Administrator","Basant Sharma"]
but i want to convert it
Administrator,Basant Sharma
using asp.net c#
CODE
protected void btnsubmit_Click(object sender, EventArgs e)
{
int val = 0;
if (textarea.Text != "")
{
string SUCode = textarea.Text; // ["Administrator","Basant Sharma"]
string[] myarray = textarea.Text.Split(',');
for (var i = 0; i < myarray.Length; i++)
{
var item = myarray[i];
// work with item here
}
for (int cnt = 0; cnt <= myarray.Length - 1; cnt++)
{
string splitComplaint = myarray[cnt];
}
}
}

That looks like JSON, and I would simply parse it as such:
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var str = "[\"Administrator\",\"Basant Sharma\"]";
var items = JsonConvert.DeserializeObject<string[]>(str);
foreach (var item in items) {
Console.WriteLine("Item: {0}", item);
}
}
}
.NET Fiddle here: https://dotnetfiddle.net/i3M8yp

This is a very naive way of doing it, but will do the trick:
protected void btnsubmit_Click(object sender, EventArgs e)
{
int val = 0;
if (textarea.Text != "")
{
string SUCode = textarea.Text;
SUCode = SUCode.Replace("\"","").Replace("[","").Replace("]","");
string[] myarray = SUCode.Split(',');
SUCode = "";
for (var i = 0; i < myarray.Length; i++)
{
SUCode += myarray[i];
if(i < myarray.Length-1)
SUCode += ",";
}
}
}

Just Loop through and replace values like below
string text = "[Administrator\",\"Basant Sharma\"]";
string result = string.Empty;
var words = text.Split(',');
for (int i = 0; i < words.Length; i++)
{
words[i] = words[i].Replace("\"", "");
words[i] = words[i].Replace("[", "");
words[i] = words[i].Replace("]", "");
if ( i == words.Length - 1)
{
result += words[i];
}
else
{
result += words[i] + ",";
}
}
Console.WriteLine(result);
Output : Administrator,Basant Sharma

Related

Windows Forms Button codes

I am trying to create/code for a search button in C# Forms.
This what I have so far:
private void btnSearch_Click(object sender, EventArgs e)
{
for (int i = 0; i < lstCustomerDB.Items.Count; i++)
{
string item = lstCustomerDB.Items[i].ToString();
if (item.Contains(txtSearch.Text))
{
index = 1;
}
}
lstCustomerDB.Items.Clear();
if (index < 0)
{
`enter code here` MessageBox.Show("Item not found.");
txtSearch.Text = String.Empty;
}
else
{
lstCustomerDB.SelectedIndex = index;
}
}
Any help would be grateful for! Thanks!
Using LINQ:
private void Search()
{
//Grab the first item that matches (or null if not found)
var firstMatch = lstCustomerDB.Items.Cast<string>()
.FirstOrDefault(x => x.Contains(txtSearch.Text));
if (firstMatch != null)
{
lstCustomerDB.SelectedItem = firstMatch;
}
else
{
MessageBox.Show("Item not found.");
txtSearch.Text = String.Empty;
}
}
Modifying your code:
int index = -1;
for (int i = 0; i < lstCustomerDB.Items.Count; i++)
{
string item = lstCustomerDB.Items[i].ToString();
if (item.Contains(txtSearch.Text))
{
index = i;
lstCustomerDB.SelectedIndex = index;
break;
}
}
if (index < 0)
{
MessageBox.Show("Item not found.");
txtSearch.Text = String.Empty;
}

C# Calculator "Input string was not in a correct format" on every operation except addition

I tried to create a small calculator and everything worked just fine. I could do every operation without an error. Then I tried to improve some things and add some.
Out of a sudden the original Part does not work anymore and i get the Error:[ System.FormatException: "Input string was not in a correct format." ] every time i try to substract, multiply or divide.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calculator_V2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
answer.Text = Calculate(textBox.Text);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string s_button = sender.ToString();
textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);
}
public string Calculate(string text)
{
double finalAnswer = AddAndSubstract(text);
return finalAnswer.ToString();
}
public double AddAndSubstract(string text1)
{
string[] text = text1.Split('-');
List<string> textList = new List<string>();
for (int i = 0; i < text.Length; i++)
{
textList.Add(text[i]);
if (i != text.Length - 1)
{
textList.Add("-");
}
textList.Add("-");
}
for (int i = 0; i < textList.Count; i++)
{
if (textList[i].Contains('+') && textList[i].Length > 1)
{
string[] testPart = textList[i].Split('+');
textList.RemoveAt(i);
for (int j = testPart.Length - 1; j >= 0; j--)
{
textList.Insert(i, testPart[j]);
if (j != 0)
{
textList.Insert(i, "+");
}
}
}
}
double total;
if (textList[0].Contains("*") || textList[0].Contains("/"))
{
total = DivideAndMultiply(textList[0]);
return total;
}
else
{
total = Convert.ToDouble(textList[0]);
for (int i = 2; i < textList.Count; i += 2)
{
if (textList[i - 1] == "-")
{
total = total - DivideAndMultiply(textList[i]);
}
else if (textList[i - 1] == "+")
{
total = total + DivideAndMultiply(textList[i]);
}
}
return total;
}
}
public double DivideAndMultiply(string text1)
{
string[] text = text1.Split('*');
List<string> textList = new List<string>();
for (int i = 0; i < text.Length; i++)
{
textList.Add(text[i]);
if (i != text.Length - 1)
{
textList.Add("*");
}
textList.Add("*");
}
for (int i = 0; i < textList.Count; i++)
{
if (textList[i].Contains('/') && textList[i].Length > 1)
{
string[] testPart = textList[i].Split('/');
textList.RemoveAt(i);
for (int j = testPart.Length - 1; j >= 0; j--)
{
textList.Insert(i, testPart[j]);
if (j != 0)
{
textList.Insert(i, "/");
}
}
}
}
double total = Convert.ToDouble(textList[0]);
for (int i = 2; i < textList.Count; i += 2)
{
if (textList[i - 1] == "/")
{
total = total / Convert.ToDouble(textList[i]);
}
else if (textList[i - 1] == "*")
{
total = total * Convert.ToDouble(textList[i]);
}
}
return total;
}
private void Button_Click_C(object sender, RoutedEventArgs e)
{
double finalAnswer = 0;
answer.Text = "";
textBox.Text = "";
}
private void Button_Click_zahl(object sender, RoutedEventArgs e)
{
string s_button = sender.ToString();
textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);
}
private void Button_Click_equals(object sender, RoutedEventArgs e)
{
answer.Text = RemoveBrackets(textBox.Text);
}
public string RemoveBrackets(string text)
{
while (text.Contains('(') && text.Contains(')'))
{
int openIndex = 0;
int closeIndex = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '(')
{
openIndex = i;
}
if (text[i] == ')')
{
closeIndex = i;
text = text.Remove(openIndex,closeIndex-openIndex +1).Insert(openIndex,ResolveBrackets(openIndex, closeIndex, text));
break;
}
}
}
for (int i = 1; i < text.Length; i++)
{
if (text[i] == '-' && (text[i]-1=='*' || text[i] - 1 == '/'))
{
for (int j=i-1; j>=0; j++)
{
if (text[j] == '+')
{
StringBuilder text1 = new StringBuilder(text);
text1[j] = '-';
text = text1.ToString();
text = text.Remove(i, 1);
break;
}
else if (text[j] == '-')
{
StringBuilder text1 = new StringBuilder(text);
text1[j] = '+';
text = text1.ToString();
text = text.Remove(i, 1);
break;
}
}
}
}
if (text[0] == '-') //für Fehler wenn - als erste Ziffer
{
text = '0' + text;
}
return Calculate(text);
}
public string ResolveBrackets(int openIndex, int closeIndex, string text)
{
string bracketAnswer = Calculate(text.Substring(openIndex +1, closeIndex -1));
return bracketAnswer;
}
}
}
Because you probably add the minus character twice
if (i != text.Length - 1)
{
textList.Add("-");
}
textList.Add("-");
Then, when you loop in step of 2
for (int i = 2; i < textList.Count; i += 2)
You don't have [number] [sign] [number] [sign] anymore.
I suggest you look and the items in your list to see the problem. I would also suggest that you split your logic into smaller methods that could individually be tested.
i think the problem is your use of
double total = Convert.ToDouble(textList[0]);
in DivideAndMultiply
First of all it's best practice to test if the string is null or empty using String.IsNullOrEmpty(textList[0]); and use Double.TryParse instead of convert.

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

How to search and replace words in a WPF TextBox?

I've found several examples that do this but with richTextBox instead. Is it even possible to replace words in a multi-line TextBox?
you can do this for searchin' the next word automatically in textbox
int t = 0;
private void FindNext(object sender, RoutedEventArgs e)
{
for (int i = t; i < NoteText.Text.Length-SearchBar.Text.Length; i++)
{
string x = "";
for (int j = 0; j < SearchBar.Text.Length; j++)
{
if(SearchBar.Text[j] == NoteText.Text[i+j])
{
x += NoteText.Text[i + j] + "";
}
else
{
x = "";
}
}
if(x == SearchBar.Text)
{
t = i+1;
NoteText.Focus();
NoteText.SelectAll();
NoteText.Select(i, SearchBar.Text.Length);
break;
}
if(i==NoteText.Text.Length - SearchBar.Text.Length - 1)
{
MessageBox.Show("The search was completed");
t = 0;
}
s = t;
}
}

csharp method that choose every second character from the word

I need a method that returns every other character in a string starting with the first character. For example, a method call with ("Java-language") returns "Jv-agae."
private static void NewMethod(string word)
{
// here comes the code
}
var str = "Java-language";
var xx = new string(str.Where((ch, index) => index % 2 == 0).ToArray());
Console.WriteLine(xx);
Or this one:
var xx = string.Join<char>("", str.Where((ch, index) => (index & 1) == 0));
probably little different then everybody else: :-)
protected static IEnumerable<char> EverySecondChar(string word)
{
for(int i = 0; i < word.Length; i += 2)
yield return word[i];
}
string result = new string(EverySecondChar("Java-language").ToArray());
Here is my suggestion for you:
private string TakeEverySecondChar(string input)
{
var result = string.Empty;
for (int i = 0; i < input.Length; i+=2)
{
result += input.Substring(i, 1);
}
return result;
}
Console.Clear();
string Lang = "Java-language";
string[] LangArr = new string[Lang.Length];
char LangChar;
for (int i = 0; i < Lang.Length; i++)
{
LangChar = Lang[i];
LangArr[i] = LangChar.ToString();
}
for (int i = 0; i < LangArr.Length; i++)
{
Console.Write(LangArr[i]);
i++;
}
Console.ReadLine();
public String strip2ndchar(string text)
{
string final="";
int i = 0;
foreach (char a in text.ToCharArray())
{
if (i % 2 == 0)
final += a;
i++;
}
return final;
}

Categories