How to extract string between same char [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I have a string "ABD-DDD-RED-Large" and need to extract "DDD-RED"
using the Split I have:
var split = "ABD-DDD-RED-Large".Split('-');
var first = split[0];
var second = split[1];
var third = split[2];
var fourth = split[3];
string value = string.Join("-", second, third);
just wondering if there's a shorter code

If you just want the second and third parts of an always 4 part (delimited by -) string you can one line it with LINQ:
string value = string.Join("-", someInputString.Split('-').Skip(1).Take(2));
An input of: "ABD-DDD-RED-Large" would give you an output of: "DDD-RED"

Not enough information. You mentioned that string is not static. May be Regex?
string input = "ABD-DDD-RED-Large";
string pattern = #"(?i)^[a-z]+-([a-z]+-[a-z]+)";
string s = Regex.Match(input, pattern).Groups[1].Value;

Use regex
var match = Regex.Match(split, #".*?-(.*?-.*?)-.*?");
var value = match.Success ? match.Groups[1].Value : string.Empty;

I'm going out on a limb and assuming your string is always FOUR substrings divided by THREE hyphens. The main benefit of doing it this way is that it only requires the basic String library.
You can use:
int firstDelIndex = input.IndexOf('-');
int lastDelIndex = input.LastIndexOf('-');
int neededLength = lastDelIndex - firstDelIndex - 1;
result = input.Substring((firstDelIndex + 1), neededLength);
This is generic enough to not care what any of the actual inputs are except the hyphen character.
You may want to add a catch at the start of the method using this to ensure there are at least two hyphen's in the input string before trying to pull out the requested substring.

Related

How to remove duplicates from a string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The code is supposed to put all letters into lower case and change j to i, which it does. But I'm trying to take out any duplicate letters.
example inputted string = jjjaaaMMM expected output string = jam
what actually happens real output string = m please help I'm not sure what I'm missing.
string key = Secret.Text;
var keyLow = key.ToLower();
var newKey = keyLow.Replace("j", "i");
var set = new HashSet<char>(newKey);
foreach (char c in set)
{
Secret.Text = Char.ToString(c);
}
Your issue is entirely the = in
Secret.Text = Char.ToString(c);
it needs to be +=
Secret.Text += Char.ToString(c);
You were overwriting each value with the next.
However you could just use linq
Secret.Text = string.Concat(key.ToLower().Replace("j", "i").Distinct());
or probably more efficiently from #Ben Voigt comments
Since you have a sequence of char, it's probably more efficient to
call the string constructor than Concat
Secret.Text = new string(set.ToArray());
// or
Secret.Text = new string(key.ToLower()
.Replace("j", "i")
.Distinct()
.ToArray());
Additional Resources
String.Concat Method
Concatenates one or more instances of String, or the String
representations of the values of one or more instances of Object.
Enumerable.Distinct Method
Returns distinct elements from a sequence.
Others may answer the question directly. I'll provide an alternative. As always with string manipulation, there's a Regex for that.
var output = Regex.Replace(input, #"(.)\1*", "$1");
You can use Linq approach:
var text = key.ToLower().Distinct().ToArray();
Don't forgot add using System.Linq

Select a part in a string C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have string
string AccountName= "123456789 - Savings - 20$"
Now I want to select the Accountname Savings only. That means the part between -s.
That data is dynamic data. So, Could you please give me an idea to get the part of string between two -s. i.e AccountName= "Savings".
Thank you in advance..!!
One of the ways you can to that:
Split string by '-'
Get the position 1 of array
Trim value to remove spaces
var AccountNameSplited= AccountName.split('-')[1].Trim();
You should be defensive in this cases:
var AccountNameBt = AccountName.Split('-');
var AccountNameBtPos1 = string.Empty;
if (AccountNameBt != null && AccountNameBt.Count() > 0)
AccountNameBtPos1 =AccountNameBt[1].Trim();
Assuming your string will always have only two -s, you could using the following to get the substring between them. If this is not the case please modify the question to better describe the issue.
string myString = AccountName.Split('-')[1];
Check out https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx for more information on the Split method in the string class.
How about:
string AccountName = "123456789 - Savings - 20$";
String[] tokens = AccountName.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
AccountName = tokens.ElementAtOrDefault(1); // Savings
If it's possible that there are no spaces:
String[] tokens = AccountName.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
AccountName = tokens.ElementAtOrDefault(1)?.Trim();
Use Regex:
AccountName = Regex.Match(AccountName, #"-\s*(.*?)\s*-").Groups[1].Value;
Demo: https://dotnetfiddle.net/3Xr24T

Replacing string literals in c# using Regex [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to replace all string literals in a string, with placeholders. For example if I have the following string:
string s1 = "foo"; string s2 = "bar"; string s3 = "baz";
I would like to replace this with:
string s1 = #0#; string s2 = #1#; string s2 = #2#;
and also retain the replaced string literals {"foo","bar", "baz"} in a data structure for later use.
I can do this through brute force ugly coding. However, I am wondering whether there is a nice way of doing this using regular expressions?
My attempt was:
MatchCollection textConstants = Regex.Matches(text, "\".*\"");
for (int i=0; i < textConstants.Count; i++)
{
text=text.Replace(textConstants[i].Value, "#" + i + "#");
}'
This does not seem very nice
And now you have two problems:
var s = "string s1 = \"foo\"; string s2 = \"bar\"; string s3 = \"baz\";";
var list = new List<string>();
var result = Regex.Replace(s, "\".*?\"", m => { list.Add(m.Value);
return "#" + (list.Count - 1) + "#"; });
Take a look at this msdn article. It's a good starting point on how to use regular expressions.
https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx

How to format a very long text on a TextBox? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to format my text in TextBox?
My text value is:
00010001008002020100010000530997000014820000148200010000012C00001482000014820000148200010000012C000014820000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101000000000000000000000000000000000000003F
And I want my output to be like this:
00010001-0080-02020100010000-53099700-00148200-00-14820001-0000-012C0000-14820000-1482000-0148-20001000-0012C000-0148-20000000-00000000-0000-00-000000000-00000000-0000-00000000-0000000-0000-00000000-00000000-00000000-0000-00000000-00-00000-000001010-00000000-000000000-0000-000000000-00000003-F
Your format must be fixed. It should not be dynamic.
I am just providing a logic you could append the further detail in regex string.
string mystring = "000100010080"
string regex = #"(\w{4})(\w{4})(\w{4})";
string strValue = Regex.Replace(mystring, regex, #"$1-$2-$3");
OUTPUT:
0001-0001-0080
EDITED: Take a look at complete example
string[] patern = "XXXXXXXX-XXXX-XXXXXXXXXXXXXX-XXXXXXXX-XXXXXXXX-XX-XXXXXXXX-
XXXX-XXXXXXXX-XXXXXXXX-XXXXXXX-XXXX-XXXXXXXX-XXXXXXXX-XXXX-
XXXXXXXX-XXXXXXXX-XXXX-XX-XXXXXXXXX-XXXXXXXX-XXXX-XXXXXXXX-
XXXXXXX-XXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXX-XXXXXXXX-XX-
XXXXX-XXXXXXXXX-XXXXXXXX-XXXXXXXXX-XXXX-XXXXXXXXX-XXXXXXXX-
X".Split('-');
string mystring = "00010001008002020100010000530997000014820000148200010000012C0
0001482000014820000148200010000012C00001482000000000000000000
0000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000001010000000000000000000000000000
00000000003F";
string regex = string.Empty;
string match = string.Empty;
for(int i=0; i<patern.Length;i++)
{
regex += #"(\w{" + patern[i].Length + "})";
match += "$" + (i + 1).ToString() + "-";
}
match = match.Substring(0, match.Length - 1);
txtMyTextBox.Text = Regex.Replace(mystring, regex, match);
Assuming that you have a fixed pattern of inserting hyphens and the string length is same every time, then you could do something like this:
int[] indices = new int[] { 2, 5, 11 };
string yourLongString = "blahblahblah";
foreach( var index in indices.Reverse() )
{
yourLongString = yourLongString.Insert( index - 1, "-" );
}
OR
Assuming you have no predefined pattern, you could insert hyphens anywhere and hence still you could use the same code above with the tweak to randomize the indices array, if needed.

Extract the first two words from a string with C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I guys im trying to workout C# code to extract the first two words from string. below is code im doing.
public static string GetDetailsAsString(string Details)
{
string Items = //how to get first 2 word from string???
if (Items == null || Items.Length == 0)
return string.Empty;
else
return Items;
}
Define "words", if you want to get the first two words that are separated by white-spaces you can use String.Split and Enumerable.Take:
string[] words = Details.Split();
var twoWords = words.Take(2);
If you want them as separate string:
string firstWords = twoWords.First();
string secondWord = twoWords.Last();
If you want the first two words as single string you can use String.Join:
string twoWordsTogether = string.Join(" ", twoWords);
Note that this simple approach will replace new-line/tab characters with empty spaces.
Assuming the words are separated by whitespaces:
var WordsArray=Details.Split();
string Items = WordsArray[0] + ' ' + WordsArray[1];

Categories