i'm looking to place a value from a text box lets say "12" to a certain place in a string temp variable. Then I want to place another value after that say "10" but with a : in between like a time. Both come from Text boxes and are validated so they can only be numbers.
If you just want to insert a value at a certain position in a string, you can use the String.Insert method:
public string Insert(int startIndex, string value)
Example:
"abc".Insert(2, "XYZ") == "abXYZc"
You can't modify strings; they're immutable. You can do this instead:
txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);
If you have a string and you know the index you want to put the two variables in the string you can use:
string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);
But if it is a simple line you can use it this way:
string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"
var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();
Related
I've assigned some string values from a data set to the string b.
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
string b = ds.Tables[0].Rows[i].ItemArray[0] + " " + ds.Tables[0].Rows[i].ItemArray[1];
}
What I want to do is add those values, and finally show as a sentence.
Example: if "dog", "cat", and "cow" are the values read by the for loop, I want to display "dog cat cow" in a message box. How to do that?
Edit: Since it appears you are interested in the String.Join() method this could work perfectly for you. You have plenty of options here but if you want to go that route here's how.
First create an array of the items you are returning then you can simple use the String.Join() method to concatenate the items in the array like so:
string separator = whatever seperator you want "," or "|"
string d = String.Join(separator, animalArray);
MessageBox.Show(d);
The first thing you'll need to do is make sure you have imported the System.Windows.Forms namespace to enable your ability to call the MessageBox function.
Essentially you are already there with the concatenation of the strings. If you are looking for a cleaner option I would recommend using String.Format() or using the newer method of concatenation by applying a '$' character in front of a string which allows you to simple add your variables between curly braces.
For example: $"Hello my name is {name}."
What's wrong with the above?
You already have them in your string variable b.
Enclose it in MessageBox.Show(); instead of adding the variable.
string b = "";
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
b += ds.Tables[0].Rows[i].ItemArray[0] + " " + ds.Tables[0].Rows[i].ItemArray[1] + "\n";
}
MessageBox.Show(b);
So, I'm making a file transfer program from one PC in my house to the other. The client can look through the server's files and take what it wants. (Makes it very easy for moving projects/documents/music). This is an example of what a string of a file looks like:
New Text Document.txt : "(FILE)-(" + f.Length + " Bytes)"
My problem is removing : "(FILE)-(" + f.Length + " Bytes)".
How can I remove JUST that part from the string? Where the f.Length is unknown...
Thanks!
Just as an alternative to the regex answers, one option is to use LastIndexOf to find the last occurence of a known part of the string (e.g. (FILE)).
var oldString = "ThisIsAString (FILE)-(1234 Bytes";
int indexToRemoveTo = oldString.LastIndexOf("(FILE)");
// Get all the characters from the start of the string to "(FILE)"
var newString = oldString.Substring(0, indexToRemoveTo);
I hope I've got what you want
string contents = "some text (FILE)-(5435 Bytes) another text";
string result = Regex.Replace(contents, #"\(FILE\)-\(\d+ Bytes\)", "");
Console.WriteLine (result);
Prints:
some text another text
Solution to remove everything after .txt
string contents = "some text .txt (FILE)-(5435 Bytes) another text";
string lastSegment = ".txt";
var result = contents.Substring(0, contents.IndexOf(lastSegment) + lastSegment.Length);
Console.WriteLine (result);
prints some text .txt
var match = Regex.Match(pattern: #"\((.*)\)-\(\d+ Bytes\)$", input: name);
if(match.Success)
{
string fileName = match.Groups[1].Value;
}
So I'm working on formatting a string and I need to line it up in a table, but this string has an undetermined number of characters. Is there anyway to have the string be in the same spot for each column? so far I have:
ostring += "Notes\t\t"
+ " : "
+ employees[number].Notes
+ "\t\t"
+ employees[number].FirstNotes
+ "\t\t"
+ employees[number].SecondNotes;
I use a similar fashion on the other rows, but they have a pre-determined number of digits, this however doesn't so I can't use the string modifiers like I would like.
Any ideas on what I need to do?
You can use String.PadRight() to force the string to a specific size, rather than using tabs.
When you are using String.Format item format has following syntax:
{ index[,alignment][ :formatString] }
Thus you can specify alignment which indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer).
Also it's better to use StringBuilder to build strings:
var builder = new StringBuilder();
var employee = employees[number];
builder.AppendFormat("Notes {0,20} {1,10} {2,15}",
employee.Notes, employee.FirstNotes, employee.SecondNotes);
You would first have to loop over every entry to find the largest one so you know hoe wide to make the columns, something like:
var notesWidth = employees.Max(Notes.Length);
var firstNotesWidth = employees.Max(FirstNotes.Length);
// etc...
Then you can pad the columns to the correct width:
var output = new StringBuilder();
foreach(var employee in employees)
{
output.Append(employee.Notes.PadRight(notesWidth+1));
output.Append(employee.FirstNotes.PadRight(firstNotesWidth+1));
// etc...
}
And please don't do a lot of string "adding" ("1" + "2" + "3" + ...) in a loop. Use a StringBuilder instead. It is much more efficient.
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();
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