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];
Related
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);
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.
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
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 9 years ago.
Improve this question
I have a string which has a following format:
"####/xxxxx"
The text before the "/" is always an integer and I need to read it. How do I get only the integer part of this string (before the "/")?
Thank you for your help.
You can split the string on / and then use int.TryParse on the first element of array to see if it is an integer like:
string str = "1234/xxxxx";
string[] array = str.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
int number = 0;
if (str.Length == 2 && int.TryParse(array[0], out number))
{
//parsing successful.
}
else
{
//invalid number / string
}
Console.WriteLine(number);
Use IndexOf and Substring:
int indexOfSlash = text.IndexOf('/');
string beforeSlash = null;
int numBeforeSlash = int.MinValue;
if(indexOfSlash >= 0)
{
beforeSlash = text.Substring(0, indexOfSlash);
if(int.TryParse(beforeSlash, out numBeforeSlash))
{
// numBeforeSlash contains the real number
}
}
Another alternative: use a regular expression:
var re = new System.Text.RegularExpression(#"^(\d+)/", RegexOptions.Compiled);
// ideally make re a static member so it only has to be compiled once
var m = re.Match(text);
if (m.IsMatch) {
var beforeSlash = Integer.Parse(re.Groups[0].Value);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string and I want to delete everything before a phrase, and then delete everything after a different phrase. i.e.,
myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words"
So the new string would be "these words I want".
Use String.Substring and String.IndexOf, it has also an overload with a start index:
string myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words";
string result = myString;
int indexOfFirstPhrase = myString.IndexOf("FIRSTPHRASE");
if(indexOfFirstPhrase >= 0)
{
indexOfFirstPhrase += "FIRSTPHRASE".Length;
int indexOfSecondPhrase = myString.IndexOf("SECONDPHRASE", indexOfFirstPhrase);
if (indexOfSecondPhrase >= 0)
result = myString.Substring(indexOfFirstPhrase, indexOfSecondPhrase - indexOfFirstPhrase);
else
result = myString.Substring(indexOfFirstPhrase);
}
Demonstration
Something like this?
string theWordsIWant = Regex.Replace(myString, #"^.*?FIRSTPHRASE\s*(.*?)\s*SECONDPHRASE.*$", "$1");
Demonstration