How to get a and b value from a text like axb? - c#

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

Related

Get the substring of the non conditional part

I have this string for example:
2X+4+(2+2X+4X) +4
The position of the parenthesis can vary. I want to find out how can I extract the part without the parenthesis. For example I want 2X+4+4. Any Suggestions?
I am using C#.
Try simple string Index and Substring operations as follows:
string s = "2X+4+(2+2X+4X)+4";
int beginIndex = s.IndexOf("(");
int endIndex = s.IndexOf(")");
string firstPart = s.Substring(0,beginIndex-1);
string secondPart = s.Substring(endIndex+1,s.Length-endIndex-1);
var result = firstPart + secondPart;
Explanation:
Get the first index of (
Get the first index of )
Create two sub-string, first one is 1 index before beginIndex to remove the mathematical symbol like +
Second one is post endIndex, till string length
Concatenate the two string top get the final result
Try Regex approach:
var str = "(1x+2)-2X+4+(2+2X+4X)+4+(3X+3)";
var regex = new Regex(#"\(\S+?\)\W?");//matches '(1x+2)-', '(2+2X+4X)+', '(3X+3)'
var result = regex.Replace(str, "");//replaces parts above by blank strings: '2X+4+4+'
result = new Regex(#"\W$").Replace(result, "");//replaces last operation '2X+4+4+', if needed
//2X+4+4 ^
Try this one:
var str = "(7X+2)+2X+4+(2+2X+(3X+3)+4X)+4+(3X+3)";
var result =
str
.Aggregate(
new { Result = "", depth = 0 },
(a, x) =>
new
{
Result = a.depth == 0 && x != '(' ? a.Result + x : a.Result,
depth = a.depth + (x == '(' ? 1 : (x == ')' ? -1 : 0))
})
.Result
.Trim('+')
.Replace("++", "+");
//result == "2X+4+4"
This handles nested, preceding, and trailing parenthesis.

Splitting text into an array of 4

I want to split text, using a char, so that I can create an object from it.
string s = "Domain_FieldName";
//string s = "Domain_Schema_TableName_FieldName";
//string s = "Domain_Schema_FieldName";
var x = s.Split(new[] {'_'}, StringSplitOptions.None);
var xx = new Response()
{
Value = "test",
DataType = "string",
Domain =
Schema =
TableName =
FieldName =
};
So, the issue is that the string to be split, could vary in length.
But I need the string to be split so that it could map to the response object fields.
I need to have a generic way to populate the response object.
So as an example, if only "Domain_FieldName" is specified, it needs to know to pass Domain to Domain on the response and FieldName to FieldName on the response, and Schema and TableName should get an empty string
You can do something like this:
var x = s.Split(new[] { '_' }, StringSplitOptions.None);
var xx = new Response
{
Value = "test",
DataType = "string",
Domain = x.Length > 0 ? x[0] : null,
Schema = x.Length > 1 ? x[1] : null,
TableName = x.Length > 2 ? x[2] : null,
FieldName = x.Length > 3 ? x[3] : null
};
Use C# Split function
string s = "Domain_Schema_TableName_FieldName";
string[] substring= s.Split('_');
The above code will split the string Domain_Schema_TableName_FieldName into different parts using the delimiter _ and will save the substrings in a string array called substring
Try checking the length of the split Array, before setting variables. (And set a default value, if it's too short)
var xx = new Response()
{
Value = "test";
DataType = "string";
Domain = (x.Length >= 1)?x[0]:"";
Schema = (x.Length >= 2)?x[1]:"";
TableName = (x.Length >= 3)?x[2]:"";
FieldName = (x.Length >= 4)?x[3]:"";
};
(also: s.Split("_") or s.Split('_') would work just as well)
EDIT:
I didn't see, that you only wanted the last 4 fields filled. Changed code
2nd EDIT:
I also didn't see that the Order of strings may be different (i.e. Example 1 vs. Example 3) . In that case i can't help you unless you can specify, how to determine which string needs to go into which field.
try this
string s = "Domain_FieldName";
var x = s.Split(new[] { '_' }, StringSplitOptions.None);
var xx = new Response
{
Value = "test",
DataType = "string",
Domain =x[0],
Schema ="",
TableName ="",
FieldName = x[1]
};
From your examples seems like Domain is always first, and FieldName always last:
string s = "Domain_FieldName";
//string s = "Domain_Schema_TableName_FieldName";
//string s = "Domain_Schema_FieldName";
var x = s.Split('_');
var xx = new Response()
{
Value = "test",
DataType = "string",
Domain = x[0]
Schema = x.Length > 2 ? x[1] : "";
TableName = x.Length > 3 ? x[2] : "";
FieldName = x.Length > 1 ? x.Last() : "";
};

How to check a String for characters NOT to be included in C#

So I have a String like:
String myString = "AAAaAAA";
I want to check the String if it contains ANY characters that are not "A"
How can I do this? my previous code is:
Regex myChecker = new Regex("[^A.$]$");
if (checkForIncluded.IsMatch(myString))
{
//Do some Stuff
}
Is there any other way to do it? The code above does not detect the small a. But when I use a different String with only characters that are not "A" it works. Thank you!
String myString = "AAAaAAA";
if(myString.Any(x => x != 'A')) {
// Yep, contains some non-'A' character
}
Try something like this:
var allowedChars = new List<char>() { 'a', 'b', 'c' };
var myString = "abcA";
var result = myString.Any(c => !allowedChars.Contains(c));
if (result) {
// myString contains something not in allowed chars
}
or even like this:
if (myString.Except(allowedChars).Any()) {
// ...
}
allowedChars can be any IEnumerable< char >.
I want to check the String if it contains ANY characters that are not
"A"
You can use Enumerable.Any like;
string myString = "AAAaAAA";
bool b = myString.Any(s => !s.Equals('A')); // True
You can use Linq:
String myString = "AAAaAAA";
var result = myString.Where(x=>x != 'A'); // return all character that are not A
if(result.Count() > 0)
{
Console.WriteLine("Characters exists other than a");
}
if you want both cases:
String myString = "AAAaAAA";
var result = myString.Where(x=>x != 'A' || x != 'a');
or Use String.Equals():
var result = myString.Where(x => !String.Equals(x.ToString(), "A", StringComparison.OrdinalIgnoreCase));
Your regular expression is only trying to match the last character. This should work:
var myString = "AAaA";
bool anyNotAs = Regex.IsMatch(myString, "[^A]", RegexOptions.None);

Get all numbers within a string c# regex

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];

How to get strings first 4 characters after first semicolon

I have a string and my requirement is that from my string I should get the first 4 characters from first semicolon(;).
I have below code:
var str1 = Settings.Default.sConstr.ToString();
var str2 = Settings.Default.dConstr.ToString();
string name = //sub string of str1 + sub string of str2;
How can we do this...?
You can use String.IndexOf and String.SubString methods like;
string s = "asdfghj;zxcvb";
var index = s.IndexOf(';');
Console.WriteLine(s.Substring(index -4, 4));
Output will be;
fghj
Here a demonstration.
If you looking 4 character AFTER semi column, you can use it like;
string s = "asdfghj;zxcvb";
var index = s.IndexOf(';');
Console.WriteLine(s.Substring(index + 1, 4));
Output will be;
zxcv
Here a demonstration.
Also checking your string contains ; character and it has 4 character after ; is a good ideas like;
if(s.Contains(';') && (s.Length >= s.IndexOf(';') + 5))
{
//Your code
}
str1.Substring(str1.IndexOf(';'), 4) + str2.Substring(str2.IndexOf(';'), 4);
or if you want 4 chars after the ; then use this one:
str1.Substring(str1.IndexOf(';') + 1, 4) + str2.Substring(str2.IndexOf(';') + 1, 4);
You can use Split() to do this.
var str1 = Settings.Default.sConstr.Split(';');
var str2 = Settings.Default.dConstr.Split(';');
string name = str1[1].Substring(0,4)+" "+str2[1].Substring(0,4);
Hope it work.
Try:
var stringToGetFrom = "some characters;Get this stuff.";
var chars = stringToGetFrom.SkipWhile(c => c != ';').Skip(1).Take(3);
// Will contain the string "Get":
var selectedString = new string(chars.ToArray());
Try this
sConstr.Split(';')[1].Substring(0,4)
Demo
string s = "asdfghj;zxcvb";
string result = s.Split(new char[]{';'})[1].Substring(0,4);
or:
string s = "asdfghj;zxcvb";
var chars = s.Split(new char[] { ';' })[1].ToCharArray().Take(4).ToArray();
string result = new string(chars);

Categories

Resources