If I copy " BOB3 27QK DEPM PJ7J T25G SJZI CJA5 BO5O|123456 " and I want to pass it to my text box, and get only the last 6 digits number in my text box, How to do in c#?
Using .Split would look like this:
string myString = "BOB3 27QK DEPM PJ7J T25G SJZI CJA5 BO5O|123456";
char[] mySplitChars = { '|' };
string[] myArray = myString.Split(mySplitChars);
Console.WriteLine(myArray[1]);
Using .Substring would look like this:
Console.WriteLine(myString.Substring(myString.Length - 6));
The latter is probably preferred because it is shorter and it does not rely on the "|" character being present. The former would be preferred if the "|" is always present but the number of characters at the end can change.
How are you passing it your text box? If it's just getting the last n characters:
refer to this answer
I have information formatted on a webpage which looks like the following:
Key=submission_id, Value=300348811884547965
Key=formID, Value=50514289063151
Key=ip, Value=xxxxx
Key=editimage, Value=Yes
Key=openimage5, Value=Yes
Key=copyimage, Value=Yes
How would I go about getting the value of each line, I was thinking of doing some sort of next() while getting all data after the 2nd equal sign of each line however I am unsure on how to do it in c#. I am sure there is a better solution then what I have in mind. Please let me know your thoughts.
A regex works nicely for parsing data structured in this way.
Regex splitter = new Regex(#"Key=([\w]+), Value=([\w]+)");
string path = "TextFile1.txt";
string[] lines = System.IO.File.ReadAllLines(path);
lines.ToList().ForEach((s) =>
{
Match match = splitter.Match(s);
if (match.Success)
{
Console.WriteLine("The Key is " + match.Groups[1] + " and the value is " + match.Groups[2]);
}
});
i have string in textbox:
`New-Value = 12,34 -- Old-Values: 12,31,`
what i'd like to do is to get Old-Value so "12,31,"
How can i get from this textbox this specific information do this? So value is between ":" and ","
Tnx
Regex.Match("New-Value = 12,34 -- Old-Values: 12,31,",#"\:(.+)\,").Groups[1].Value.Trim()
const string oldPointer = "Old-Values: ";
var text = "New-Value = 12,34 -- Old-Values: 12,31,";
var old = text.Substring(text.IndexOf(oldPointer) + oldPointer.Length).TrimEnd(',');
Not very clear if this is a fixed (static) format of your string, but by the way:
A simple solution could be:
string str = "New-Value = 12,34 -- Old-Values: 12,31,";
str.Substring(str.IndexOf(':') + 1);
More complex one should involve Regular expressions, like an answer of L.B or others if any.
The string, when displayed looks like: value1, value2, value3, value4, value5 etc..
What I want the string to do once I display it is (removing spaces and commas, i assume I can use index + 2 or something to get past the comma):
value1
value2
etc...
lastKnownIndexPos = 0;
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(unformatedList, ",?")) //Currently is ',' can I use ', '?
{
list += unformatedList.Substring(lastKnownIndexPos, m.Index - 1) + "\n\n"; //-1 to grab just the first value.
lastIndex = m.Index + 2; //to skip the comma and the space to get to the first letter of the next word.
//lastIndex++; //used this to count how many times it was found, maxed at 17 (have over 100):(
}
//MessageBox.Show(Convert.ToString(lastIndex)); //used to display total times each was found.
MessageBox.Show(list);
At the moment the message box does not show any text, but using the lastIndex I get a value of 17 so I know it works for part of it :P
That's easy (I'm using System.Linq here):
var formatted = string.Join("\n\n", unformatedList.Split(',').Select(x => x.Trim()));
MessageBox.Show(formatted);
An alternative approach, as swannee pointed out, would be the following:
var formatted = Regex.Replace(unformatedList, #"\s*,\s*", "\n\n").Trim();
Edit:
To make the above examples work regardless of how you use the result string, you should use Environment.NewLine instead of "\n".
One way is to simply replace the ", " with a newline.
MessageBox.Show( unformatedList.Replace(", ", "\n") );
Or heck, why not just use string.Replace?
var formatted = unformattedList.Replace(", ", "\n\n");
I have a string "8329874566".
I want to place - in the string like this "832-98-4566"
Which string function can I use?
I would have done something like this..
string value = "8329874566";
value = value.Insert(6, "-").Insert(3, "-");
You convert it to a number and then format the string.
What I like most about this is it's easier to read/understand what's going on then using a few substring methods.
string str = "832984566";
string val = long.Parse(str).ToString("###-##-####");
There may be a tricky-almost-unreadable regex solution, but this one is pretty readable, and easy.
The first parameter of the .Substring() method is where you start getting the characters, and the second is the number of characters you want to get, and not giving it sets a default as value.length -1 (get chars until the end of the string):
String value = "8329874566";
String Result = value.Substring(0,3) + "-" + value.Substring(3,2) + "-" + value.Substring(6);
--[edit]--
Just noticed you didn't use one of the numbers AT ALL (number '7') in the expected result example you gave, but if you want it, just change the last substring as "5", and if you want the '7' but don't want 5 numbers in the last set, let it like "5,4".
Are you trying to do this like American Social Security numbers? I.e., with a hyphen after the third and and fifth numerals? If so:
string s = "8329874566";
string t = String.Format("{0}-{1}-{2}", s.Substring(0, 3), s.Substring(3, 2), s.Substring(5));
Just out of completeness, a regular expression variant:
Regex.Replace(s, #"(\d{3})(\d{2})(\d{4})", "$1-$2-$3");
I consider the Insert variant to be the cleanest, though.
This works fine, and I think that is more clear:
String value = "8329874566";
value = value.Insert(3, "-").Insert(6, "-");
The console outputs shows this:
832-98-74566
If the hyphens are to go in the same place each time, then you could simply concatenate together the pieces of the orginal string like this:
// 0123456789 <- index
string number = "8329874566";
string new = number.Substring(0, 3) + "-" + number.Substring(3, 2) + "-" + number.Substring(5);
For a general way of making mutable strings, use the StringBuilder class. This allows deletions and insertions to be made before calling ToString to produce the final string.
You could try the following:
string strNumber = "8329874566"
string strNewNumber = strNumber.Substring(0,3) + "-" + strNumber.Substring(4,2) + "-" strNumber.Substring(6)
or something in this manner
string val = "832984566";
string result = String.Format("{0}-{1}-{2}", val.Substring(0,3), val.Substring(3,2), val.Substring(5,4));
var result = string.Concat(value.Substring(0,3), "-", value.Substring(3,2), "-", value.Substring(5,4));
or
var value = "8329874566".Insert(3, "-").Insert(6, "-");
Now how about this for a general solution?
// uglified code to fit within horizontal limits
public static string InsertAtIndices
(this string original, string insertion, params int[] insertionPoints) {
var mutable = new StringBuilder(original);
var validInsertionPoints = insertionPoints
.Distinct()
.Where(i => i >= 0 && i < original.Length)
.OrderByDescending(i => i);
foreach (int insertionPoint in validInsertionPoints)
mutable.Insert(insertionPoint, insertion);
return mutable.ToString();
}
Usage:
string ssn = "832984566".InsertAtIndices("-", 3, 5);
string crazy = "42387542342309856340924803"
.InsertAtIndices(":", 1, 2, 3, 4, 5, 6, 17, 200, -1, -1, 2, 3, 3, 4);
Console.WriteLine(ssn);
Console.WriteLine(crazy);
Output:
832-98-4566
4:2:3:8:7:5:42342309856:340924803
Overkill? Yeah, maybe...
P.S. Yes, I am regex illiterate--something I hope to rectify someday.
A straightforward (but not flexible) approach would be looping over the characters of the string while keeping a counter running. You can then construct a new string character by character. You can add the '-' character after the 3rd and 5th character.
A better approach may be to use a function to insert a single character in the middle of the string at a specific index. String.Insert() would do well. The only thing to pay attention to here is that the string indexes will get off by one with each insert.
EDIT more language-specific as per comments