I am at a loss as to how to do this. I am printing some information to a richtextbox that will be multiple lines, has words and numbers. I need to search the richtextbox for specific numbers and if they are there, set them to a string to be used later. Say the box contains User: Matt User's number: 9 I want to have a string labeled UserNum so that I can have something like Messagebox.Show("The User's Number is " + UserNum); and have it show up as The User's Number is 9.
Originally I thought this would work...
if (richtextbox1.Text.Contains(" 9") == true)
{
UserNum = "9";
Messagebox.Show("The User's Number is " + UserNum);
}
How could I go about doing this? The name and number will be on the same line and the name will be varying lengths so I can't just have it look at a set spot in the box. The number itself also can range from 1 to 30 so I would need to either repeat an if command 30 times or put a range.
Edit: There is potential for there to be other lines that might also contain numbers outside of the 1-30 range.
With regex, you can have:
string pattern = #"[0-9]+";
string input = #"Matt's number for today
is 33 and OK.";
RegexOptions options = RegexOptions.Multiline;
Console.WriteLine("Matt's number is: {0}", Regex.Matches(input, pattern, options)[0].Value);
It seems like regular expressions might be useful here. Otherwise, if you know there will only be one number in the textbox, you could select all the chars that are digits and initialize a new string from the array:
var digitArray = richtextbox1.Text.Where(Char.IsDigit).ToArray();
string userNum = new String(digitArray);
Messagebox.Show("The User's Number is " + userNum);
You can use a Linq query to find the number like below:
var nums = Enumerable.Range(1,30).Select(x => x.ToString());
var num = richtextbox1.Text.Split(' ')
.Where(x => numStr.Contains(x))
.Single();
Console.WriteLine("The user number is " + num);
Use String.Split to parse the string into an array
Iterate array and use Int32.TrParse method to determine if the "word" is in fact a number
var input = "User: Matt User's number: 10";
int num = 0;
foreach(var word in input.Split(' '))
{
if (Int32.TryParse(word, out num) && Enumerable.Range(1,30).Contains(num))
{
Console.WriteLine("The user number is " + num);
break;
}
}
or with linq:
int testNum;
var digits = input.Split(' ').Where(a => Int32.TryParse(a, out testNum) && Enumerable.Range(1, 30).Contains(testNum)).FirstOrDefault();
Console.WriteLine("Linq The user number is " + (!string.IsNullOrEmpty(digits) ? digits : "Not Found"));
Related
I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?
For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting
"START":"13/08/1410:30:00"
Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)
If the split position is always 17, then simply:
string t = s.Substring(0, 17) + " " + s.Substring(17);
Obviously you will have to sort the numbers out, but thats the general idea.
String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);
Or you can use the StringBuilder class:
var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
if (i == 17)
finalString.Add(" ");
else
finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();
If the date time format always the same you can use string.Insert method
var output = #"""START"":""13/08/1410:30:00""".Insert(17, " ");
Strings in .Net are immutable: you can never change them. However, you can easily create a new string.
var date_time = dateString + " " + timeString;
Is there a way in c# to look at a defined number of char in a string?
meaning -
I have the following number
336-5010-0000-00-10 that needs to change to this number - 336-5993-0000-00-10
I only want to check if the 2nd segment of numbers are between 2999 and 6000
I am reading this data from a CSV, I just don't want this statement a million times
if (columns[0].Contains(“5010”)) columns[0] = columns[0].Replace(“5010”, #”5993”);
string test = "336-5010-0000-00-10";
string foo = Regex.Replace(test, #"(\d+\-)(2999|[3-5][0-9]{3}|6000)((-\d+){3})", "${1}5993${3}");
Alternative crazy LINQ answer:
string foo2 = string.Join("-", from number in test.Split('-').Select((str, index) => new { str = str, index = index })
let num = Convert.ToInt32(number.str)
select number.index == 1 && num >= 2999 && num <= 6000 ? "5993" : number.str);
http://dotnetfiddle.net/yzROoK
Edit: More obvious regex.
you want to
split the string on the '-' character into a string[] called stringParts
convert stringParts[1] to an integer
perform validation of the integer value from step 2
string[] stringParts = columns[0].Split('-');
int valueOfConcern = Convert.ToInt32(stringParts[1]);
if (valueOfConcern >= 2999 && valueOfConcern <= 6000)
{
//take your action
}
string numberStr = "336-5010-0000-00-10";
int number = int.Parse(numberStr.Substring(4, 4));
numberStr.Substring(4, 4) gives you only the four-digit number starting at the 4th character, which int.Parse() converts into a number.
Then you can test that number is between your specified range, replace it, etc.
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 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
I am generating 35 strings which have the names ar15220110910, khwm20110910 and so on.
The string contains the name of the Id (ar152,KHWM), and the date (20110910). I want to extract the Id, date from the string and store it in a textfile called StatSummary.
My code statement is something like this
for( int 1= 0;i< filestoextract.count;1++)
{
// The filestoextract contains 35 strings
string extractname = filestoextract(i).ToString();
statSummary.writeline( extractname.substring(0,5) + "" +
extractname.substring(5,4) + "" + extractname.substring(9,2) + "" +
extractname.substring(11,2));
}
When the station has Id containing 5 letters, then this code executes correctly but when the station Id is KHWM or any other 4 letter name then the insertion is all messed up. I am running this inside a loop. So I have tried keeping the code as dynamic as possible. Could anyone help me to find a way without hardcoding it. For instance accessing the last 8 elements to get the date??? I have searched but am not able to find a way to do that.
For the last 8 digits, it's just:
extractname.Substring(extractname.Length-8)
oh, I'm sorry, and so for your code could be:
int l = extractname.Length;
statSummary.WriteLine(extractname.substring(0,l-8) + "" +
extractname.Substring(l-8,4) + "" + extractname.Substring(l-4,2) + "" +
extractname.Substring(l-2,2));
As your ID length isn't consistent, it would probably be a better option to extract the date (which is always going to be 8 chars) and then treat the remainder as your ID e.g.
UPDATED - more robust by actually calculating the length of the date based on the format. Also validates against the format to make sure you have parsed the data correctly.
var dateFormat = "yyyyMMdd"; // this could be pulled from app.config or some other config source
foreach (var file in filestoextract)
{
var dateStr = file.Substring(file.Length-dateFormat.Length);
if (ValidateDate(dateStr, dateFormat))
{
var id = file.Substring(0, file.Length - (dateFormat.Length+1));
// do something with data
}
else
{
// handle invalid filename
}
}
public bool ValidateDate(stirng date, string date_format)
{
try
{
DateTime.ParseExact(date, date_format, DateTimeFormatInfo.InvariantInfo);
}
catch
{
return false;
}
return true;
}
You could use a Regex :
match = Regex.Match ("khwm20110910","(?<code>.*)(?<date>.{6})" );
Console.WriteLine (match.Groups["code"] );
Console.WriteLine (match.Groups["date"] );
To explain the regex pattern (?<code>.*)(?<date>.{6}) the brackets groups creates a group for each pattern. ?<code> names the group so you can reference it easily.
The date group takes the last six characters of the string. . says take any character and {6} says do that six times.
The code group takes all the remaining characters. * says take as many characters as possible.
for each(string part in stringList)
{
int length = part.Length;
int start = length - 8;
string dateString = part.Substring(start, 8);
}
That should solve the variable length to get the date. The rest of the pull is most likely dependent on a pattern (suggested) or the length of string (when x then the call is 4 in length, etc)
If you ID isn't always the same amount of letters you should seperate the ID and the Date using ',' or somthing then you use this:
for( int 1= 0;i< filestoextract.count;1++)
{
string extractname = filestoextract[i].ToString();
string ID = extractname.substring(0, extractname.IndexOf(','));
string Date = extractname.substring(extractname.IndexOf(','));
Console.WriteLine(ID + Date);
}