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 8 years ago.
Improve this question
I need to search through a string array to find every occurrence of "Parameters Table", and between each "Parameters Table" and the next, get another string from a specified index (that remains constant). I have been doing this like so:
public List<string> findlistOfNames(string[] arrayToLookForNames)
{
List<string> listOfNames = new List<string>();
const string separator = "Parameters Table"; //This is the string I am searching for
var cuttedWords = arrayToLookForNames.SkipWhile(x => x != separator).Skip(1);
while (cuttedWords.Any())
{
var variable = cuttedWords.TakeWhile(x => x != separator).ToArray();
cuttedWords = cuttedWords.Skip(variable.Length + 1);
listOfNames.Add(variable[2]); //This (always index 2) needs to be added to the list
}
return listOfNames;
}
This runs very slowly. Is there a better way to do this?
EDIT: Here is a snippet of string[] arrayToLookForNames:
Parameters Table
0
41
Baro Pressure
hPa
AFD2
recorded
Parameters Table
0
42
Baro Setting
in-hg
Seeing as you haven't specified what happens in the following case:
Parameters TableewfihweifhweParameters TableihwefwihewfParameters Table
where there are a total of 3 possible matches, I've chosen to assume that there's only one match per entry.
You could use regular expressions to state this somewhat more succinctly. Will probably be more efficient than your method too...
var regex = new Regex(#"(?<=Parameters Table).*?(?=(?:Parameters Table)|$)");
IEnumerable<string> foundValues =
arrayToLookForNames.SelectMany(x => regex.Matches(x))
.Where(m => m.Success)
.Select(m => m.Value);
... for the entry above, this would yield ewfihweifhwe
to cater for your better specified requirements:
var regex = new Regex(#"(?<=Parameters Table).*?(?=(?:Parameters Table)|$)",
RegexOptions.Singleline);
var vals = arrayToLookForNames
.SelectMany(x=>regex.Matches(x).Cast<Match>())
.Where(m=>m.Success)
.Select(m=>m.Value);
Related
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
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 to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
ok I have no idea on how to do this and i have tried looking up how to do this but nothing good came up so ill ask it here. So what i am trying to do is:
string input = TextEditor.text; <-- this is in windows form application and
The "TextEditor" is the textbox for input
i want to take the string (which is input from the texct box) then split it so each word is on every other line like so:
if input = "hi my name is is"
out put should be:
hi: 1
my: 1
name: 1
is: 2 <-- if the word is said it shouldn't be repeated.
could someone please help me? I am a true newbie and i am completely lost. I don't have any code yet because I DONT KNOW HOW TO DO THIS!
Use Linq GroupBy and Count:
string inputText = "hi my name is is";
var words = inputText.Split(' ').ToList();
var wordGroups = words.GroupBy(w => w).Select(grp => new {
Word = grp.Key,
Count = grp.Count()
});
string outputText = string.Join("\n", wordGroups.Select(g => string.Format("{0}:\t{1}", g.Word, g.Count)));
/*
hi: 1
my: 1
name: 1
is: 2
*/
Split the input string into an array, then use that to build a dictionary. If the word is already in the dictionary, increment it. Otherwise add it with an initial value of 1.
string input = TextEditor.text;
string[] inputWords = input.Split(' ');
Dictionary<string, int> wordCounts = new Dictionary<string, int>();
foreach (string word in inputWords)
{
if (wordCounts.ContainsKey(word))
{
wordCounts[word]++;
}
else
{
wordCounts.Add(word, 1);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to do Regex from a website url, but it gets me an error:
Specified argument was out of the range of valid values
Regex re = new Regex("\"id\":\"([0 - 9] +)\"");
string ree = re.Matches(sr)[0].Value;
MessageBox.Show(ree);
The url output is just blank page with text. http://prntscr.com/a6xyi0
You have to move all the spaces you don't want match, you can use [0-9]+ or \d+
You can iterate over all matches for every id in the string:
Regex re = new Regex("\"id\":\"(?<id>\\d+)\"");
string[] ree = re.Matches(sr).Cast<Match>().Select(m => m.Value).ToArray();
// Or if you just want the id:
string[] ree = re.Matches(sr).Cast<Match>().Select(m => m.Groups["id"].Value).ToArray();
foreach (var item in ree)
{
//do something
}
EDIT:
If you want add the results to a ListView then this should work for you:
var sr = "{\"id\":\"11111\", ...} {\"id\":\"22222\", ...} {\"id\":\"33333\", ...} {\"id\":\"44444\", ...}";
Regex re = new Regex("\"id\":\"(?<id>\\d+)\"");
var ree = re.Matches(sr).Cast<Match>().Select(m => m.Groups["id"].Value);
foreach (var item in ree)
{
var lvItem = new ListViewItem(new string[] { item, "who column" });
listView.Items.Add(lvItem);
}
And you will get some like this:
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];