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);
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
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.
I want to split a long string (that contains only numbers) to string arr 0f numbers with 8 digits after the comma.
for example:
input:
string str = "45.00019821162.206580920.032150970.03215097244.0031982274.245303020.014716900.046867870.000198351974.613444580.391664580.438532450.00020199 3499.19734739 0.706802871.145335320.000202002543.362378010.513759201.659094520.000202102.391733720.000483371.65957789"
output:
string[] Arr=
"
45.00019821 162.20658092 234.03215097 123123.03215097
255.00019822 74.24530302 23422.01471690 1.04686787
12.00019835 1974.61344458 234.39166458 123212.43853245
532.00020199 3499.19734739 878.70680287 1.14533532
1234.00020200 2543.36237801 23.51375920 1.65909452
12221.00020210 2.39173372 0.00048337 1.65957789"
EDIT:
I try use
String.Format("{0:0.00000000}", str);
or some SubString such as:
public static string GetSubstring(string input, int count, char delimiter)
{
return string.Join(delimiter.ToString(), input.Split(delimiter).Take(count));
}
with no success.
You can split the string using Regex:
var strRegex = #"(?<num>\d+\.\d{8})";
var myRegex = new Regex(strRegex, RegexOptions.None);
foreach (Match myMatch in myRegex.Matches(str))
{
var part = myMatch.Groups["num"].Value;
// convert 'part' to double and store it wherever you want...
}
More compact version:
var myRegex = new Regex(#"(?<num>\d*\.\d{8})", RegexOptions.None);
var myNumbers = myRegex.Matches(str).Cast<Match>()
.Select(m => m.Groups["num"].Value)
.Select(v => Convert.ToDouble(v, CultureInfo.InvariantCulture));
The input string str can be converted to the desired output as follows.
static IEnumerable<string> NumberParts(string iString)
{
IEnumerable<char> iSeq = iString;
while (iSeq.Count() > 0)
{
var Result = new String(iSeq.TakeWhile(Char.IsDigit).ToArray());
iSeq = iSeq.SkipWhile(Char.IsDigit);
Result += new String(iSeq.Take(1).ToArray());
iSeq = iSeq.Skip(1);
Result += new String(iSeq.Take(8).ToArray());
iSeq = iSeq.Skip(8);
yield return Result;
}
}
The parsing method above can be called as follows.
var Parts = NumberParts(str).ToArray();
var Result = String.Join(" ", Parts);
This would be the classical for-loop version of it, (no magic involved):
// split by separator
string[] allparts = str.Split('.');
// Container for the resulting numbers
List<string> numbers = new List<string>();
// Handle the first number separately
string start = allparts[0];
string decimalPart ="";
for (int i = 1; i < allparts.Length; i++)
{
decimalPart = allparts[i].Substring(0, 8);
numbers.Add(start + "." + decimalPart);
// overwrite the start with the next number
start = allparts[i].Substring(8, allparts[i].Length - 8);
}
EDIT:
Here would be a LINQ Version yielding the same result:
// split by separator
string[] allparts = str.Split('.');
IEnumerable<string> allInteger = allparts.Select(x => x.Length > 8 ? x.Substring(8, x.Length - 8) : x);
IEnumerable<string> allDecimals = allparts.Skip(1).Select(x => x.Substring(0,8));
string [] allWholeNumbers = allInteger.Zip(allDecimals, (i, d) => i + "." + d).ToArray();
The shortest way without regex:
var splitted = ("00000000" + str.Replace(" ", "")).Split('.');
var result = splitted
.Zip(splitted.Skip(1), (f, s) =>
string.Concat(f.Skip(8).Concat(".").Concat(s.Take(8))))
.ToList()
Try it online!
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)));
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);