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
Related
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"));
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;
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);
I need help. I tried to split a String, but I did not find the perfect way.
Example:
string data = "Car1#4$doors&1$engine&100$horsepower&2$color"
I want to split this string. The result is also a string and should look like 4 doors, 1 engine, 100 horsepower, 2 color.
Any ideas?
var res = string.Join(", ", data.Substring(data.IndexOf("#") + 1).Replace("$", " ").Split('&'));
Here's the ugliest line I could come up with to answer your question.
Enjoy!
Console.WriteLine(string.Join("\r\n", "Car1#4$doors&1$engine&100$horsepower&2$color".Split('#').Select(s => s.Replace("&", ", ").Replace('$', ' '))));
Here is one implementation, of course you can remove the matching {0}
string data = "Car1#4$doors&1$engine&100$horsepower&2$color";
string[] dataArray = data.Split('#');
string carProperties = dataArray[1].Replace("$", " ").Replace('&', ',');
Console.WriteLine("{0} {1}", dataArray[0], carProperties);
API returns string as follows: "error=OK\neta=2 - 3 Days\nprice=24.18"
Besides using substring with start/stop index and or splitting everything by delimiter characters and into a word array can I just pick out the value after "nprice=" and from "neta=" to (before "\")" straight away ?
You could use yourString.Split(new[] { #"\n" }, StringSplitOptions.None) to get a list of the substrings.
However, my preference would be to turn this into a dictionary:
var yourString = #"error=OK\neta=2 - 3 Days\nprice=24.18";
var lookup = (from sub in yourString.Split(new[] { #"\n" }, StringSplitOptions.None)
let parts = sub.Split(new[] { '=' }, 2)
select parts).ToDictionary(p => p[0], p => p[1]);
You would then use this like so:
var error = lookup["error"];
var eta = lookup["eta"];
var price = Convert.ToDecimal(lookup["price"]);
Console.WriteLine("Error Code: {0}, ETA: {1}, Price: {2:C}", error, eta, price);