I have a string which can have values like
"Barcode : X 2
4688000000000"
"Barcode : X 10
1234567890123"
etc.
I want to retrieve the quantity value (i.e., 2, 10) and the barcode value (i.e., 4688000000000, 1234567890123)
I tried the following code -
string[] QtyandBarcode = Regex.Split(NPDVariableMap.NPDUIBarcode.DisplayText, #"\D+");
But when I execute, I'm getting QtyandBarcode as a string array having 3 values -
""
"2"
"4688000000000"
How do I prevent the null value from being stored?
You could do this:
MatchCollection m = Regex.Matches(NPDVariableMap.NPDUIBarcode.DisplayText, #"\d+");
var x = (from Match a in m select a.Value).ToArray();
string[] QtyandBarcode = Regex.Split(NPDVariableMap.NPDUIBarcode.DisplayText, #"\D+").Where(s => !string.IsNullOrEmpty(s)).ToArray();
now you can
string qty = QtyandBarcode[0];
string barcode= QtyandBarcode[1];
What about this simple approach.
string[] parts = NPDVariableMap.NPDUIBarcode.DisplayText.split(' '); //split on space
string qty = parts[1];
string barcode = parts[2];
Related
I am facing a problem with how to get a specific string value from a text. For example: for a given string
"400X500 abc"
How can I get some string from that text like:
string width = "400"
string height = "500"
Thank you so much for your help.
Best Regards,
Cherry Truong
You can try regular expressions in order to extract numbers
using System.Text.RegularExpressions;
...
string source = "400X500 abc";
string[] numbers = Regex
.Matches(source, "[0-9]+")
.OfType<Match>()
.Select(match => match.Value)
.ToArray();
string width = numbers.ElementAtOrDefault(0) ?? "";
string height = numbers.ElementAtOrDefault(1) ?? "";
Or (if you want to be sure that X delimiter is present)
Match match = Regex
.Match(source, #"([0-9]+)\s*X\s*([0-9]+)", RegexOptions.IgnoreCase);
string width = match.Success ? match.Groups[1].Value : "";
string height = match.Success ? match.Groups[2].Value : "";
You can try something like this:
string data = "400X500 abc";
string[] splitData = data.TrimEnd('a', 'b', 'c').Trim().Split('X');
string width = splitData[0] ?? string.Empty;
string height = splitData[1] ?? string.Empty;
If you can assume that it will always be in that format, you can do something like this:
string raw = "400X500";
string width = raw.Substring(0, raw.IndexOf("X"));
string height = raw.Substring(raw.IndexOf("X") + 1);
Now width="400" and height=500.
Assuming the text is always going to be in the format "100X200 aabdsafgds", then a working solution would look something like:
var value = "100X200 aabdsafgds";
var splitValues = value.Split(new[] { 'X', ' ' }, StringSplitOptions.RemoveEmptyEntries);
var value1 = splitValues[0];
var value2 = splitValues[1];
I assume the input string is always in the same format.
"heightXwidth abc"
var value = "400X500 abc";
var vals = value.Trim().Split('X');
var height = new string(vals[0] == null ? "0".ToArray() : vals[0].Where(char.IsDigit).ToArray());
var width = new string(vals[1] == null ? "0".ToArray() : vals[1].Where(char.IsDigit).ToArray());
I'm sure you could adjust as needed.
EDIT:
I adjusted the code to avoid the issues as pointed out in the comments and ensure you only get the numbers from the string
How to count 2 or 3 letter words of a string using asp csharp, eg.
string value="This is my string value";
and output should look like this
2 letter words = 2
3 letter words = 0
4 letter words = 1
Please help, Thanks in advance.
You can try something like this:
split sentence by space to get array of words
group them by length of word (and order by that length)
iterate through every group and write letter count and number of words with that letter count
code
using System.Linq;
using System.Diagnostics;
...
var words = value.Split(' ');
var groupedByLength = words.GroupBy(w => w.Length).OrderBy(x => x.Key);
foreach (var grp in groupedByLength)
{
Debug.WriteLine(string.Format("{0} letter words: {1}", grp.Key, grp.Count()));
}
First of all you need to decide what counts as a word. A naive approach is to split the string with spaces, but this will also count commas. Another approach is to use the following regex
\b\w+?\b
and collect all the matches.
Now you got all the words in a words array, we can write a LINQ query:
var query = words.Where(x => x.Length >= 2 && x.Length <= 4)
.GroupBy(x => x.Length)
.Select(x => new { CharCount = x.Key, WordCount = x.Count() });
Then you can print the query out like this:
query.ToList().ForEach(Console.WriteLine);
This prints:
{ CharCount = 4, WordCount = 1 }
{ CharCount = 2, WordCount = 2 }
You can write some code yourself to produce a more formatted output.
If i understood your question correctly
You can do it using dictionary
First split the string by space in this case
string value = "This is my string value";
string[] words = value.Split(' ');
Then loop trough array of words and set the length of each word as a key of dictionary, note that I've used string as a key, but you can modify this to your needs.
Dictionary<string, int> latteWords = new Dictionary<string,int>();
for(int i=0;i<words.Length;i++)
{
string key = words[i].Length + " letter word";
if (latteWords.ContainsKey(key))
latteWords[key] += 1;
else
latteWords.Add(key, 1);
}
And the output would be
foreach(var ind in latteWords)
{
Console.WriteLine(ind.Key + " = " + ind.Value);
}
Modify this by wish.
I'm trying to get the table name from a string that is in the format:
[schemaname].[tablename]
I think this can be done with split but not sure how to handle the trailing ] character.
A simple approach is using String.Split and String.Trim in this little LINQ query:
string input = "[schemaname].[tablename]";
string[] schemaAndTable = input.Split('.')
.Select(t => t.Trim('[', ']'))
.ToArray();
string schema = schemaAndTable[0];
string table = schemaAndTable[1];
Another one using IndexOf and Substring:
int pointIndex = input.IndexOf('.');
if(pointIndex >= 0)
{
string schema = input.Substring(0, pointIndex).Trim('[', ']');
string table = input.Substring(pointIndex + 1).Trim('[', ']');
}
//find the seperator
var pos = str.IndexOf('].[');
if (pos == -1)
return null; //sorry, can't be found.
//copy everything from the find position, but ignore ].[
// and also ignore the last ]
var tableName = str.Substr(pos + 3, str.Length - pos - 4);
Just to be the different here is another version with regex;
var result = Regex.Match(s, #"(?<=\.\[)\w+").Value;
Split by 3 characters. i.e [.] with option RemoveEmptyEntries that is pretty self explanatory.
var result = input.Split(new [] {'[','.',']'}, StringSplitOptions.RemoveEmptyEntries);
Try this:
var tableAndSchema = "[schemaname].[tablename]";
var tableName = tableAndSchema
.Split('.')[1]
.TrimStart('[')
.TrimEnd(']');
Split will split the string on the . character and turn it into an array of two strings:
[0] = "[schemaname]"
[1] = "[tablename]"
The second (index 1) element is the one you want. TrimStart and TrimEnd will remove the starting and ending brackets.
Another way to do this is with Regular Expressions:
var tableAndSchema = "[schemaname].[tablename]";
var regex = new Regex(#"\[.*\].\[(.*)\]");
var tableName = regex.Match(tableAndSchema).Groups[1];
The regex pattern \[.*\].\[(.*)\] creates a capture group for the characters within the second pair of brackets and lets you easily pull them out.
var res = input.Split('.')[1].Trim('[', ']');
Another LINQ solution:
var tableName = String.Join("", input.SkipWhile(c => c != '.').Skip(1)
.Where(c => Char.IsLetter(c)));
I have a single string that i want to compare against a list of strings to find the best match.
For example,
string search = "Orange Black Red One Five"
the List of strings could contain the following
l[0] = "Orange Seven Three Black"
l[1] = " Nine Eight Seven Six"
l[2] = " Black Blue Purple Red Five Four Nine Ten"
l[0] contains 2 matches
l[1] contains 0 matches
l[2] contains 3 matches
so the program would choose l[2] as the best match, with a 60% match.
How would I compare two strings like this?
var s = search.Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries);
var res1 = (from string part in l
select new
{
list = part,
count = part.Split(new char[] {' '}).Sum(p => s.Contains(p) ? 1 : 0)
}).OrderByDescending(p=> p.count).First();
Console.Write(res1.count);
Split the strings in to arrays.
Determine the number of matches.
Divide.
...
Profit!
Code:
double Compare(string a, string b)
{
var aWords = a.Split(' ');
var bWords = b.Split(' ');
double matches = (double)aWords.Count(x => bWords.Contains(x));
return matches / (double)aWords.Count();
}
Edit: Or, if you just want to get the match count...
int Matches(string a, string b)
{
var aWords = a.Split(' ');
var bWords = b.Split(' ');
return aWords.Count(x => bWords.Contains(x));
}
I'd like to split a string using the Split function in the Regex class. The problem is that it removes the delimiters and I'd like to keep them. Preferably as separate elements in the splitee.
According to other discussions that I've found, there are only inconvenient ways to achieve that.
Any suggestions?
Just put the pattern into a capture-group, and the matches will also be included in the result.
string[] result = Regex.Split("123.456.789", #"(\.)");
Result:
{ "123", ".", "456", ".", "789" }
This also works for many other languages:
JavaScript: "123.456.789".split(/(\.)/g)
Python: re.split(r"(\.)", "123.456.789")
Perl: split(/(\.)/g, "123.456.789")
(Not Java though)
Use Matches to find the separators in the string, then get the values and the separators.
Example:
string input = "asdf,asdf;asdf.asdf,asdf,asdf";
var values = new List<string>();
int pos = 0;
foreach (Match m in Regex.Matches(input, "[,.;]")) {
values.Add(input.Substring(pos, m.Index - pos));
values.Add(m.Value);
pos = m.Index + m.Length;
}
values.Add(input.Substring(pos));
Say that input is "abc1defg2hi3jkl" and regex is to pick out digits.
String input = "abc1defg2hi3jkl";
var parts = Regex.Matches(input, #"\d+|\D+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
Parts would be: abc 1 defg 2 hi 3 jkl
For Java:
Arrays.stream("123.456.789".split("(?<=\\.)|(?=\\.)+"))
.forEach((p) -> {
System.out.println(p);
});
outputs:
123
.
456
.
789
inspired from this post (How to split string but keep delimiters in java?)
Add them back:
string[] Parts = "A,B,C,D,E".Split(',');
string[] Parts2 = new string[Parts.Length * 2 - 1];
for (int i = 0; i < Parts.Length; i++)
{
Parts2[i * 2] = Parts[i];
if (i < Parts.Length - 1)
Parts2[i * 2 + 1] = ",";
}
for c#:
Split paragraph to sentance keeping the delimiters
sentance is splited by . or ? or ! followed by one space (otherwise if there any mail id in sentance it will be splitted)
string data="first. second! third? ";
Regex delimiter = new Regex("(?<=[.?!] )"); //there is a space between ] and )
string[] afterRegex=delimiter.Split(data);
Result
first.
second!
third?