Select a part in a string C# [closed] - c#

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

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

How do I split a string with '$' delimiter? [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 4 years ago.
Improve this question
I have this FINAL PAYMENT $25 string on a MVC c# application.
I want to split into FINAL PAYMENT and 25
I tried doing this
string s = "FINAL PAYMENT $25";
string[] str1 = s.Split('$');
//result: 25
How can I get the rest. Can anyone help?
Split method returns a string array, if you need both elements of this array, Try:
string s = "FINAL PAYMENT $25";
string[] resArray = s.Split('$');
var FPayment = resArray[0];
var second25= resArray[1];
You can use indexOf instead of a Split
string s = "FINAL PAYMENT $25";
int index = s.IndexOf("$");
String final_pay = s.Substring(index + 1);

How to extract string between same char [closed]

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.

How can I extract sub-string from string in c# code? [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 6 years ago.
Improve this question
How can I extract this sub-string "60684" from this string "/fa/Viewer/Switcher/60684/0" in c#?
You can use Split method :
string str = "/fa/12012/Switcher/60684/0";
string str2 = str.Split('/')[4];
One way is to use regex:
static void Main()
{
string pattern = #"\/[a-zA-Z]+\/[a-zA-Z]+\/[a-zA-Z]+\/([0-9]+)\/[a-z0-9]+";
var regex = new Regex(pattern);
string path = "/fa/Viewer/Switcher/60684/0";
var match = regex.Match(path);
Console.WriteLine(match.Groups[1].ToString());
}
Like this:
string url = #"/fa/12012/Switcher/60684/0";
string[] NumberAfterSwitcher = url.Split('/');
string num = (NumberAfterSwitcher.Length > 3) ? (String)url.Split('/').GetValue(3) : String.Empty;

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