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.
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"));
string containsCharacter = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(containsCharacter).Length - 1;
I originally pulled this code off another person's question's answer but it doesn't seem to work with text boxes.
Errors I'm getting:
The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Argument 1: cannot convert from 'string' to 'char[]'
I prefer to fix this code rather than use other things like LINQ but I would accept it if there isn't a way to fix this code.
You could iterate through the characters
string value = "BANANA";
int x = 0;
foreach (char c in value)
{
if (c == 'A')
x++;
}
string containsCharacter = "t";
string testString = "test string contains certain characters";
int count = testString.Count(x => x.ToString() == containsCharacter);
This example will return 6.
The Split version you are using expects a character as input. This is the version for strings:
string containsText = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(new string[]{containsText}, StringSplitOptions.None).Length - 1;
With this code, count will be: 1 if textBox1.Text includes "test", 6 if it contains "t", etc. That is, it can deal with any string (whose length might be one, as a single character, or as big as required).
You can call ToCharArray on the string to make it a char[], like this:
int count = testString.Split(containsCharacter.ToCharArray()).Length - 1;
Since Split takes characters as a param, you could rewrite this by listing the characters being counted directly, as follows:
int count = testString.Split(',', ';', '-').Length - 1;
"this string. contains. 3. dots".Split(new[] {"."}, StringSplitOptions.None).Count() - 1
Edit:
Upon Reading your code more carefully I suggest you do this, you should rephrase your question to
"Check the number of occurences of a certain string in Another string":
string containsString = "this";
string test = "thisisateststringthisisateststring";
var matches = Regex.Matches(test,containsString).Count;
matches is 2!
My initial post answers your actual question "occurrences of a certain character in a string":
string test = "thisisateststring";
int count = test.Count(w => w == 'i');
Count is 3!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.
So if i have a string like this
546546555
desired output:
546,546,555
Other times, the number could be longer or shorter:
254654
desired output:
254,654
Is it possible to split in this manner then join with a comma?
tahnks!
EDIT:
Hi Everyone,
Thanks very much for your help.
To add to this post I also found a way to do this in SQL:
SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]
Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:
Example
int value = 546546555;
string displayValue = value.ToString("#,#");
See this MSDN page for different format values:
C - Currency format
D - Decimal format
E - Scientific format
F - Fixed point format
G - General format
N - Number format
P - Percent format
R - Round trip format
X - Hexadecimal format
You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:
var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
formatted = value.ToString("#,#");
}
Live example: http://rextester.com/FHO11833
Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:
string splitter(string tosplit, int num, string splitstring)
{
string output = "";
for (int i = 0; i < tosplit.Length; i += num)
if (i + num < tosplit.Length)
output += tosplit.Substring(i, num) + ",";
else
output += tosplit.Substring(i);
return output;
}
Here, the output of splitter("546546555", 3, ",") would be 546,546,555
This would not be ideal for numbers though, as the other answers would cover this case perfectly.
Not very good code, but it works.
public static string GetString(string val, int number)
{
List<string> res = new List<string>();
res.Add("");
int counter = 0, i = 0;
while (i < val.Length)
{
while (res[counter].Length < number && i < val.Length)
{
res[counter] += val[i];
i++;
}
res.Add("");
counter++;
}
return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
}
val - your input string
number - number of characters you want to split, equals to 3 in your case
Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.
var val = 12345678;
CultureInfo c = CultureInfo.CurrentCulture;
Application.CurrentCulture = new CultureInfo("EN-us");
var s = String.Format("{0:#,#}", val);
Application.CurrentCulture = new CultureInfo("ES-es");
var i = String.Format("{0:#,#}", val);
Application.CurrentCulture = c;
I want to use c# format to do this:
6 = "000006"
999999 = "999999"
100 = "000100"
-72 = error
1000000 = error
I was trying to use String.Format but without success.
Formatting will not produce an error if there are too many digits. You can achieve a left-padded 6 digit string just with
string output = number.ToString("000000");
If you need 7 digit strings to be invalid, you'll just need to code that.
if (number >= 0 and number < 1000000)
{
output = number.ToString("000000")
}
else
{
throw new ArgumentException("number");
}
To use string.Format, you would write
string output = string.Format("{0:000000}", number);
Suppose I have a string "011100011".
Now I need to find another string by adding the adjacent digits of this string, like the output string should be "123210122".
How do I split each characters in the string and manipulate them?
The method that I thought was to convert the string to integer using Parsing and splitting each character using modulus or something and performing operations on them.
But can you suggest some simpler methods?
Here's a solution which uses some LINQ plus dahlbyk's idea:
string input = "011100011";
// add a 0 at the start and end to make the loop simpler
input = "0" + input + "0";
var integers = (from c in input.ToCharArray() select (int)(c-'0'));
string output = "";
for (int i = 0; i < input.Length-2; i++)
{
output += integers.Skip(i).Take(3).Sum();
}
// output is now "123210122"
Please note:
the code is not optimized. E.g. you might want to use a StringBuilder in the for loop.
What should happen if you have a '9' in the input string -> this might result in two digits in the output string.
Try converting the string to a character array and then subtract '0' from the char values to retrieve an integer value.
string input = "011100011";
int current;
for (int i = 0; i < input.Length; i ++)
{
current = int.Parse(input[i]);
// do something with current...
}