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
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
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method:
private string RemoveFromList(string sentence)
{
var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" };
var control = lists.Any(sentence.Contains);
string result;
if (control)
{
var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains)
?? throw new InvalidOperationException(), StringComparison.Ordinal);
result = index != -1 ? sentence.Remove(index) : sentence;
}
else
result = sentence;
return result;
}
var str = "ask- This is a sentence.";
Message.Box(RemoveFromList(str));
// It does not give to me: This is a sentence.
This method does not work properly. It does not remove the keyword from the string.
Using string.Replace is the simplest approach:
foreach (var word in lists)
{
sentence = sentence.Replace(word,"").Trim();
}
Although that will find the word in the middle of the string too. If you wanted to remove it only at the start you could use IndexOf check it's 0 and then take the string starting from word.Length using Substring. Or use StartsWith:
foreach (var word in lists)
{
if (sentence.StartsWith(word))
{
sentence = sentence.Substring(word.Length).Trim();
// break; // if only one
}
}
There are 2 options for you.
First of all the Remove usage is incorrect. You just want to remove the keyword. If u pass 1 argument to remove it will remove from that index till end. Pass the length of keyword as second arg to Remove.
s.Remove(index, len);
If string contains it than replace the occurrence of keyword with empty string
s.Replace("keyword", "");
Another option is you could create an extension since you already know what items to remove.
using System.Text.RegularExpressions;
public static string RemoveFromList(this string sentence)
{
new List<string>{ "ask-",
"que-",
"(app)",
"(exe)",
"(foo)" }.ForEach(name =>
{
sentence = Regex.Replace(sentence.Replace(name, string.Empty), " {2,}", " ");
});
return sentence;
}
Useage
var str = "ask- This is (app) a que- sentence.".RemoveFromList();
Note
I used Regex.Replace as it's possible you may have some blank spaces floating around after you remove the bad string/s, this helps ensure that doesn't happen.
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 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 7 years ago.
Improve this question
I have files on a local server with the address of \\localServerAddress\Folder\Program.exe. I need to remove the server address dynamically and replace it with a different server address that is being selected elsewhere in the form. The server names can be different lengths, therefore, I can not use the string.Substring function.
So given the input
\\localServerAddress\Folder\Program.exe
I would like the result
\\differentServerAddress\Folder\Program.exe
If you are always working with UNCs
Then
string toRemove = new Uri(yourString).host;
string newString = yourString.Replace(String.format(#"\\{0})",toRemove)
, String.format(#"\\{0})",whateveryouwant));
Use this method:
string changeServerInPathString(string originalString, string newServer)
{
List<string> stringParts = originalString.TrimStart('\\').Split('\\').ToList();
stringParts.RemoveAt(0);
stringParts.Insert(0, newServer);
return string.Join("\\", stringParts.ToArray()).Insert(0, "\\\\");
}
You can use something like this:
void Main()
{
string path = #"\\localServerAddress\Folder\Program.exe";
UriBuilder bld = new UriBuilder(path);
bld.Host = "NewServer";
Console.WriteLine(bld.Uri.LocalPath);
}
Result: \\newserver\Folder\Program.exe
string text = #"\\test\FolderName\foo.exe";
text = text.Replace('\\', '-'); \\ this is done as I was not able to make the regex **\\\\\\(.)*?\\** , work.
Regex rg = new Regex("--.*?-"); \\ if in case the above mentioned regex is made to work correctly please replace the regex with the same.
text = rg.Replace(text, "");
Console.WriteLine(text.Replace('-', '\\'));
Console.Read();
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
Need help to find C# code to do a SQL-type like search (case insensitive)
could you please help me with regex code for this. Pattern and test candidates are both user input
* could be anywhere. so pattern could be .T*S.com
e.g.
Pattern = *.test.com
Test Candidate1 = abc.test.com Result = Pass
Test Candidate2 = abc.tESt.com Result = Pass
Test Candidate3 = abc.itest.com Result = FAIL
In case the * is at the front you can use String.EndsWith().
Like
"abc.test.com"
.EndsWidth(".test.com", StringComparison.InvariantCultureIgnoreCase);
returns true.
If you don't want to go the regex route and the candidate always ends with .test.com you can get rid of the * in your pattern and then check with EndsWith:
if (candidate.EndsWith(pattern, StringComparison.InvariantCultureIgnoreCase))
// you have a match
If you want the regex, the pattern is need to be:
public bool IsMatch(string s,string pattern)
{
return System.Text.RegularExpressions.Regex.IsMatch(s, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
}
string pattern = ".*\.test\.com"
Console.WriteLine(IsMatch("abc.test.com",pattern).ToString()); //PASS
Console.WriteLine(IsMatch("abc.tESt.com",pattern).ToString()); //PASS
Console.WriteLine(IsMatch("abc.itest.com",pattern).ToString()); //FAIL
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];