remove the last second character from string - c#

I had a query string end with :
where id in (.....,11,)
and I want to remove the last "," to work correct I try this :
string test = id_case[i];
id_case[i] = test.Substring(Math.Max(0,test.Length -2));
id_case[i] += test.Substring(Math.Max(test.Length-1,test.Length)) + ")";
but didn't work the whole " where .... " is disappear
any help ?

This will remove the last comma in your query string:
var q = "where id in (.....,11,)";
q = q.Remove(q.LastIndexOf(','),1);

It would probably be cleaner to remove the comma at the source, but one method is to do:
string[] parts = test.Split(',');
test = string.Join(",",parts.Take(parts.Length - 1))
+ parts[parts.Length-1);

Related

C# Sort / Order a textBox with given Values

I want to sort / order a multiline textbox with given values, but it seems I do something wrong. It does not sort / order. \r\n has also no effekt. The values were created by hand for testing.
Could someone please help me?
string[] test = { "2021-12-08 2020-04-12 2021-06-15 2022-11-28 2019-01-12" };
//string[] test = { "2021-12-08" + "2020-04-12" + "2021-06-15" + "2022-11-28" + "2019-01-12" }; Also tested and with whitespace.
IEnumerable<string> query = test.OrderBy(i => i.ToString());
foreach (string r in query)
{
textBox2.Text = r.ToString()+"\r\n";
}

Get a specific word from a line read from a .txt

right now I am reading some lines from a .txt.
Lets say, a user enters his name and in the .txt will be saved "Logged in {username} on 13/04/2016 at 10:55 am".
(Just an example.)
Now I want to read the .txt and print only specific parts into a textbox.
Meaning, in the textbox shall appear "{Username} - 13/04/2016 - 10:55 am".
So far, I am able to read from the .txt and print the whole line.
private void button_print_results_Click(object sender, RoutedEventArgs e)
{
int counter = 0;
string actual_line;
System.IO.StreamReader file_to_read =
new System.IO.StreamReader("myText.txt");
while ((actual_line = file_to_read.ReadLine()) != null)
{
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
file_to_read.Close();
}
Is there a way, to reach this without overwriting the whole file?
And no, I can't change the format how the names etc. are saved.
(I used them here for a better understanding, the actual lines I need to read/check are different and auto-generated).
I don't expect full working code, it would be just great if you could tell me for which commands I need to look. Been a long time since I last worked with c#/wpf and I never worked much with Streamreader...
Thanks
I think regular expressions is the best tool for what you're trying to achieve. You can write something like this:
Regex regex = new Regex("Logged in (?<userName>.+) on (?<loginTime>.+)");
while ((actual_line = file_to_read.ReadLine()) != null)
{
Match match = regex.Match(actual_line);
if (match.Success) {
string loginInfo = string.Format("{0} - {1}", match.Groups["userName"], match.Groups["loginTime"]);
textBox_results.Text = textBox_results.Text +"\n"+ loginInfo;
}
}
There are couple of possible solutions for this. One most straight forward way for your case would be to use Substring and Replace.
Since the earlier string is always Logged in (note the last space) and you simply want to get the rests of the string after the phrase, replacing only the preposition of time words (" on ", " at ") with dash (" - ") you could take advantage on that:
string str = "Logged in {username} on 13/04/2016 at 10:55 am";
string substr = str.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
In your implementation, this is how it look like:
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
(Note: the solution above assumes the {username} does not contain spaced preposition of time words - which would almost likely be the case for a {username})
You could split the actual_line String so you get an array of Strings. And then fill the Strings you want to show in the TextBox into it.
string[] values = actual_line.Split(' ');
textBox_results.Text = textBox_results.Text + "\n" + values[2] + " " + values[6] + " " + values[7];
The text in the TextBox for example is "{username} 10:55 am"
You can use Regex for better performances as #Dmitry-Rotay suggested in the previous comment, but if you jave a not-so-big file your loop+string manipulations is an acceptable compromise.
Always use Environment.NewLine instead of "\n", it's more portable.
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line
.Replace(("Logged in "), String.Empty)
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text
+ System.Environment.NewLine
+ actual_line;
counter++;
}

use int array in string in c#

I have a int array with for example {1,2,3,4} value.
I want to put this numbers into, for example, my list box like this :
listBox2.Items.Add("After Inserting (" + page[i].ToString() + ')' + <use all my numbers like this : 1234 here>+"Page Fault = " + pf.ToString());
Output :
After Inserting (3) 1234 page fault = 5
1234 is just an example. My array is much bigger.
How can I do that in c#?
You can use String.Join (actually the IEnumerable<T> overload is taken):
String joined = String.Join("", yourArray);
i'm new in c# how i dont know how place the string among the text
You can use String.Format to build the text and to increase readability:
var inserted = page[i].ToString();
var allInserted = String.Join("", yourArray);
var pageFault = pf.ToString();
var itemText = String.Format("After Inserting ({0}) {1} page fault = {2}"
,inserted, allInserted, pageFault);
listBox2.Items.Add(itemText);
Edit 2:
can i replace some Character instead one number in array? my array :
{1,2,3,4,-1"} output : 1,2,3,4,empty
Yes, you can replace the output:
String.Join("", yourArray.Where(i => i != -1));
Edit 3:
i understand how i can exclude -1 but i didn't understand how i can
replace something with that...like "empty" instead -1
Here we go ...
String.Join(", ", intArray.Select(i => i == -1 ? "empty" : i.ToString()));
string.Join(", ", intArray.Select(i => i.ToString()))
string.Join works also with ToList()
int[] numbers = new int[] {1,2,3,4,5};
string s = string.Join("", numbers.ToList());
Console.WriteLine(s);
output is = "12345"
EDIT: I don't know the name of your array, so I still use the above numbers example
listBox2.Items.Add("After Inserting (" + page[i].ToString() + ") " +
string.Join("", numbers.ToList()) +
" Page Fault = " + pf.ToString());
EDIT:
To exclude numbers like -1 then
int[] numeri = new int[] {1,2,3,4,5,-1};
string s = string.Join(",", numeri.Where(i => i != -1).ToList());
Console.WriteLine(s);
Note, added a comma to separate the numbers

split and increase in asp .net

I have productID="ab1002" which is in string format.
productID is not always start with ab it might be xy,ptz.So i want to split the numeric part of ID and increase by 1.
means
string productID="ab1002";
want a result
string newProductID="ab1003";
How to get this.thanks for help.
To remove the characters:
string sNumbers = Regex.Replace(productID,"[^A-Z][a-z]",String.Empty); // To remove letters
string sText = Regex.Replace(productID,"[^0-9]",String.Empty); // To remove numbers
string iTmp = int.Parse(sNumbers); // Convert to integer
iTmp++;
string newProductID = sText + iTmp.ToString();
Would you please try with below code, this works fine according to you, thanks for your time
productID = (Regex.Replace(productID, "[0-9]", String.Empty)) +
(Convert.ToInt32(Regex.Replace(productID, "[a-z]", string.Empty, RegexOptions.IgnoreCase)) + 1).ToString();

How can i trim or remove " , " at the end of my query?

i try to write a query but my query finished with "Control nvarchar(500), ". i want to finish "Control nvarchar(500)" How can remove ",", " "?
void SqlTable(List listMyColumnNames, string TableName)
{
string Text = "Create table ENG_"+TableName+" (ENG_"+TableName+"_ID integer PRIMARY KEY identity(1,1), ";
char[] MyChar = {',', ' ' };
for (int i = 0; i < listMyColumnNames.Count; )
{
Text+=listMyColumnNames[i]+" nvarchar(500), ";
if (i == listMyColumnNames.Count-1)
Text.TrimEnd(MyChar);
i++;
}
Text+=" )";
I think you may want to look at String.Join. What you can do is transform your column name strings, containing the SQL definition of your colum, e.g. MyColumnName[1]+" nvarchar(500)", into alistMyColumnDefarray, thenJoin` that array with the comma as a separator.
The benefit:
no 'if I'm the last entry',
clear separation of your column names and your SQL representation for a column
The drawbacks.... none :)
for( String name in listMyColumnNames ) {
listMyColumnDefs.Add( name + " nvarchar(500)" );
}
String mycolumndef = String.Join( listMyColumnDefs, ", ");
There are many ways to fix this, but here's the problem in your code:
if (i == listMyColumnNames.Count-1)
Text.TrimEnd(MyChar); // doesn't work like this!
String is immutable: you can't invoke a method on it and expect it to be mutated by the method. TrimEnd instead returns a new String, so what you need to do is:
Text = Text.TrimEnd(MyChar); // now works fine!
Related questions
Why string.Replace(“X”,“Y”) works only when assigned to new string?
for (int i = 0; i < listMyColumnNames.Count; ++i)
{
Text += listMyColumnNames[i] + " nvarchar(500)";
if (i < listMyColumnNames.Count-1)
Text += ", ";
}
Or you could just remove your Trim call and add `Text = Text.Replace(", )", " )");' at very end.
Have you thought about using the StringBuilder object to build your string, rather than concatenating yours string in a loop!
http://www.yoda.arachsys.com/csharp/stringbuilder.html

Categories

Resources