Extract part of the string based on delimiters [closed] - c#

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
I need help to develop a logic that will extract part of the string when the user enter a "delimiter"
For example:
string data = "|cBlue|pDaisy|pRose|mTomato|mWheat|pCabbage|p100 units|d19.0";
string userInput = //User enter input
So, if the user enters "|c", it should return "Blue"
If the user enters "|m", it should return "Tomato", "Wheat" as 2 strings.
If the user enters "|p", it should return "Daisy", "Rose", "Cabbage" and "100 units" as 4 different strings.
If the user enters something that is not exist, say for example, |z, it will return nothing or an empty string "".
Note: This is just a sample data, the actual data consists of |a - |z, |A - |Z

Start with string.Split() to tokenize the string.
Then iterate over each token. Pull out its first character and construct a Dictionary<char, string> using the first character as a key and the remainder as a value.
Then simply do a dictionary lookup on the desired character to find the relevant token.

First get the input,parse it.Use Split method then filter the words by first letter,Something like this:
var userInput = Console.ReadLine();
if(userInput.Length == 2)
{
var words = data.Split(userInput[0]).Where(x => x.StartsWith(userInput[1].ToString()));
if(words.Any())
{
var result = words.Select(x => x.Substring(1)).ToList();
}
else
{
// no word found
}
}

Related

fill out secretword with guessedword in C# [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 last year.
Improve this question
I am working on a word guessing game.
there are secret words and guessed words for this game. The secret word should be hidden from the user, for example, if the secret word is "Hello" then the result will be ".....".
My question is that if I guess a correct letter for the secret word and I want to put this correctly guessed letter in its actual place in the original word, for example, if the secret word is "Hello" and someone types "e", The result should look like (. e . . .)
You can use String.Insert(Int32, String) method to update your secret string.
You learn about it more from its documentation : https://learn.microsoft.com/en-us/dotnet/api/system.string.insert?view=net-6.0
Also, here is a quick example of its usage
class Program
{
private static string _actualWord = "HELLO";
private static string _secret = ".....";
static void Main(string[] args)
{
Console.WriteLine($"The Secret Word is: {_secret}");
Console.WriteLine("\nPlease guess a letter");
string guess = Console.ReadLine();
if (_actualWord.Contains(guess))
{
int index = _actualWord.IndexOf(guess);
_secret = _secret.Insert(index, guess);
Console.WriteLine($"Result: {_secret}");
}
else
{
Console.WriteLine("\nIncorrect Guess");
}
Console.ReadLine();
}
}
Output

how do you take a string then organize the words in it with how many times the word occurs in c#? [closed]

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);
}
}

Strings with parameters for a method in C# [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 6 years ago.
Improve this question
My sentence is: !doar 12345, rayantt
Using string.Contains(!doar), I need get the other values as:
int mount = 12345;
string destiny = "rayannt";
Let the input be the input string as you stated in the question, searchString be the string that you wanted to search for; strParam and intParam are the two required outputs; Now consider the following code:
string input = "!doar 12345, rayantt";
string searchString = "!doar";
string strParam=string.Empty ;
int intParam=0;
if (input.Contains(searchString)) // check for the existence of the search string in given string
{
input = input.Replace(searchString, ""); // remove the searchstring from the input
string[] contents = input.Split(',');
int.TryParse(contents[0], out intParam); // collect the integer param
strParam=contents[1]; // collect the string param
}
// here you get 12345 in intParam and "rayantt" in strParam

c# how to get specific 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 8 years ago.
Improve this question
Hi I am facing problem to get specific string. The string as below:
string myPurseBalance = "Purse Balance: +0000004000 556080";
I want to get 4000 out only.
if your string format/pattern is fix then you can get specific value
string myPurseBalance = "Purse Balance: +0000004000 556080";
//
var newPursebal =Convert.ToDouble(myPurseBalance.Split('+')[1].Split(' ')[0]);
You can use this regular expression:
string extract = Regex.Replace(myPurseBalance, #"(.*?)\: \+[0]*(?<val>\d+) (.*)", "${val}")
It searches for the decimals after :, trims the leading 0s and removes everything after the last whitespace.
You can use string.Split to get the +0000004000 and then use string.Substring to get the last four characters by passing the Length-4 as starting index.
string str = myPurseBalance.Split(' ')[2];
str = str.Substring(str.Length-4);
Learn Regex . Here is just simple tutorial
using System;
using System.Text.RegularExpressions;
namespace regex
{
class MainClass
{
public static void Main (string[] args)
{
string input = "Purse Balance: +0000504000 556080";
// Here we call Regex.Match.
Match match = Regex.Match(input, #"\+[0]*(\d+)",
RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// Finally, we get the Group value and display it.
string key = match.Groups[1].Value;
Console.WriteLine(key);
}
}
}
}

How do I capture integers from a string in C#? [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 9 years ago.
Improve this question
In this project I need to separate the Booking ID from the string below into a separate integer.
Booking ID: 27620
Booked for Paitient(ID): 003
Booked Staff ID: 001
Booked Room: b001
Booked Equipment: Adam
How do I do this in C#?
To clarify: The code above is the whole string, the first line is where the booking ID is contained. I need help finding a way to separate the ID from the string.
I have tried Regex but to no prevail. I cannot get my head around the string formatting.
The ID can be any length.
Regex can handle what you are looking for.
string text = "Booking ID: 27620 ...";
foreach (string line in new LineReader(() => new StringReader(text))
{
string result = Regex.Replace(line, #"[^\d]", "");
Console.WriteLine(result); // >> 27620
}
The regex "[^\d]" says:
[] Capture
^\d Everything that is not (^) a digit (\d)
Then the Replace replaces it all with an empty string.
This would be most valuble if you were looping through each line of your file.
If you needed to keep the field value, then running a simple split would be the better way to go.
string input = "Booking ID: 27620";
Dictionary<string, string> dict =
new Dictionary<string, string>{key = input.Split(':')[0],
value = input.Split(':')[1]};

Categories