Get common part between two strings c# [closed] - c#

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 6 years ago.
Improve this question
What I need is to get the common part between two words and get the differences too.
Examples:
Scenario 1
word1 = Testimonial
word2 = Test
Will return
Common part Test, difference imonial
Scenario 2
word1 = Test
word2 = Testimonial
Will return
Common part Test, difference imonial
Scenario 3
word1 = Testimonial
word2 = Tesla
Will return
Common part Tes, difference timonial and la
The common part of both words are always on the beginning.
In other words, I need to preserve the begin of the word until the words get different, than I need to get the differences.
I'm trying to do that avoid using a lot of if's and for's.
Thank you guys.

LINQ alternative:
string word1 = "Testimonial", word2 = "Tesla";
string common = string.Concat(word1.TakeWhile((c, i) => c == word2[i]));
string[] difference = { word1.Substring(common.Length), word2.Substring(common.Length) };

class Program
{
static void Main(string[] args)
{
string word1 = "Testimonial";
string word2 = "Tesla";
string common = null;
string difference1 = null;
string difference2 = null;
int index = 0;
bool same = true;
do
{
if (word1[index] == word2[index])
{
common += word1[index];
++index;
}
else
{
same = false;
}
} while (same && index < word1.Length && index < word2.Length);
for (int i = index; i < word1.Length; i++)
{
difference1 += word1[i];
}
for (int i = index; i < word2.Length; i++)
{
difference2 += word2[i];
}
Console.WriteLine(common);
Console.WriteLine(difference1);
Console.WriteLine(difference2);
Console.ReadLine();
}
}

You can use Intersect and Except to get it:
static void Main(string[] args)
{
var string1 = "Testmonial";
var string2 = "Test";
var intersect = string1.Intersect(string2);
var except = string1.Except(string2);
Console.WriteLine("Intersect");
foreach (var r in intersect)
{
Console.Write($"{r} ");
}
Console.WriteLine("Except");
foreach (var r in except)
{
Console.Write($"{r} ");
}
Console.ReadKey();
}
Note that this is a simple solution. For example:
Except would not work if you change the order of the strings, like :
"Test".Except("Testmonial");

Related

Hi i'm a newbie in c# and i'm trying to write trimleft function by myself [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 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
public static string TrimLeft(string word)
{
int numberOfLetters = 0;
foreach (var c in word)
{
numberOfLetters++;
}
int start = 0, end = numberOfLetters - 1;
string b = "";
for (int i = 0; i < numberOfLetters; i++)
{
if (!char.IsWhiteSpace(word[i]))
{
start = i;
b += word[i];
}
}
Console.WriteLine("Trimmed version: {0}", b);
return word;
}
i'm trying to write trimleft function by myself i couldnt quite figure out how i did the normal trim version but how can i do the trimleft version of it without using any inbuilt string. functions like substring etc.
this is a shorter version, it was tested and working properly
public static string TrimLeft(string word)
{
string result = "";
bool trimDone = false;
foreach (var chr in word)
{
if (chr == ' ' && !trimDone) continue;
result = result + chr;
trimDone = true;
}
Console.WriteLine("Trimmed version: {0}", result);
return result;
}
test
var word = " abc def !";
word = TrimLeft(word);
result
abc def !
Somebody could suggest a string builder, but as I understand it is out of the scope of the project
also there is another version but I think that it is out of the scope too
public static string TrimLeft(string word)
{
var i = 0;
foreach (var chr in word)
{
if (chr != ' ')
{
if ( i > 0)
{
Console.WriteLine($"Trimmed version:{word[i..]}");
return word[i..];
}
else break;
}
i++;
}
Console.WriteLine($"Nothing To Trim : {word}");
return word;
}
Find the index of the first non-space character in your input string, then copy the rest to your result string and return it.
The first non-space char can be found with a loop and the copy operation can also be done with a loop, if IndexOf or Substring are not allowed when solving this problem. A string builder could be used to efficiently build your result string.
Another way to do it is:
public static string TrimLeft(string word)
{
int i = 1;
foreach (var chr in word)
{
if (chr != ' ') break;
i++;
}
i--;
return word[i..];
}
see: Fiddle

How to get all string "possibilities" [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 2 years ago.
Improve this question
Given a string like string s = "a(b)cd(ef)",
what is the best way to get a list/array containing all the following strings:
"acd",
"abcd",
"acdef",
"abcdef"
Additional information:
The order of the result doesn't matter.
The amount of parenthesis is unknown
I have tried to do this with RegEx, but didn't get very far.
There are many ways to do this, however here is an example using a mask array to keep track of the permutation state, some regex, and a few helper methods
Given
// work out the states of the combination
public static bool GetNextState(bool[] states)
{
for (var i = 0; i < states.Length; i++)
if ((states[i] = !states[i]) == true)
return false;
return true;
}
// Create the combination
public static string Join(string[] split, string[] matches, bool[] states)
{
var sb = new StringBuilder();
for (var i = 0; i < states.Length; i++)
sb.Append(split[i] + (states[i]? matches[i]:""));
sb.Append(split.Last());
return sb.ToString();
}
// enumerate the results
public static IEnumerable<string> Results(string input)
{
var matches = Regex.Matches(input, #"\(.+?\)")
.Select(x => x.Value.Trim('(', ')'))
.ToArray();
var split = Regex.Split(input, #"\(.+?\)");
var states = new bool[matches.Length];
do {
yield return Join(split, matches, states);
} while (!GetNextState(states));
}
Usage
string s = "a(b)cd(ef)";
foreach (var result in Results(s))
Console.WriteLine(result);
Output
acd
abcd
acdef
abcdef
Full Demo Here
Michael Randall's answer is correct, but after some more thinking I was finally able to come up with a (probably not very good) working solution as well
string s = "a(b)cd(ef)";
List<string> result = new List<string>();
int amount = s.Split('(').Length;
amount = (int)Math.Pow(2, amount - 1);
for (int i = 0; i < amount; i++)
{
string temp = string.Copy(s);
string binaryString = Convert.ToString(i, 2).PadLeft(amount, '0');
string tempResult = "";
for (int j = 0; j < binaryString.Length && !temp.Equals(""); j++)
{
Regex regex = new Regex(#"[^(]*");
tempResult += regex.Match(temp).Value;
if (binaryString[binaryString.Length - 1 - j].Equals('1'))
{
string regexStr = #"\(([^)]*)\)";
regex = new Regex(regexStr);
tempResult += regex.Match(temp).Value;
}
if (temp.Contains(')'))
temp = temp.Substring(temp.IndexOf(')') + 1);
else temp = "";
}
result.Add(tempResult.Replace("(", "").Replace(")", ""));
}

how to get words from string without SPLIT in c# [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 2 years ago.
Improve this question
I'm stack with a task which ask for "read from console" (C#) a text (string) and get words separated by spaces.
for example: phrase=**"i love this world love"** BUT I need to try this WITHOUT methods or functions like SPLIT or REGEX or similar.
I need to compare 2 words and I dont know how to catch 'em in separated word1 word2 fullphrase.
What i want is word1="this" word2= "world" AND CHECK if there are 2 words REPEATED
string frase, palabra1="",pal2="";
bool si = false;
Console.WriteLine("Entra frase");
frase = Console.ReadLine();
int j = 0;
for (int i = 0; i < frase.Length; i++)
{
if (frase[i] != ' ')
{
palabra1 += frase[i];
if (pal2 == palabra1) si = true;
}
else
{
pal2 = palabra1;
palabra1 = "";
}
}
if (si == true) Console.WriteLine($" SI HAY palabras seguidamente
repetidas ");
else Console.WriteLine($"NO HAY PALABRAS REPETIDAS AQUI");
If you can't use any functions(split, regex, indexOf, etc), then what you should do is loop through each character of the text, and push the currently processed segment into your word list when you reach a (white)space.
String testString = "This is a test string ";
ArrayList words = new ArrayList();
string currentWord = "";
foreach(char c in testString)
{
if(Char.IsWhiteSpace(c))
{
if(currentWord.Length > 0)
{
words.Add(currentWord);
currentWord = "";
}
}
else
{
currentWord+=c;
}
}

How to use a foreach loop to pick required words from an array? [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 3 years ago.
Improve this question
I want to pick class names of all classes from given input code. However my code is picking just one class name. What should I do?
I am working on a Windows form in C#. I have tried to it do with a foreach loop but it is not working
private void btnDetect_Click(object sender, EventArgs e)
{
// splitting code
string mystr = richTextBox1.Text;
if (mystr.ToLower().Contains("class"))
{
string[] splitText = mystr.Split(new char[] { ' ' });
foreach (string word in splitText)
{
int classindex = Array.FindIndex(splitText, r => r.Contains("class"));
string className = splitText[classindex + 1];
MessageBox.Show(className);
}
}
else
MessageBox.Show("class not found");
}
}
I expect the output to show all the class names in the input, but the output I get is only the first class name
Array.FindIndex always returns the first index because the condition never changes.
You could use:
string[] tokens = mystr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
List<string> classList = new List<string>();
for (int i = 0; i < tokens.Length - 1; i++)
{
if (tokens[i].Equals("class", StringComparison.InvariantCultureIgnoreCase))
classList.Add(tokens[++i]);
}
you could use this method :
public IEnumerable<string> GetClasses(string str)
{
if (!str.Contains("Class", StringComparison.OrdinalIgnoreCase)) yield break;
string[] words =str.Split(' ', StringSplitOptions.RemoveEmptyEntries);
int wordsCount = words.Length;
for (var index = 0; index < wordsCount; index++)
{
string word = words[index];
if (!word.Equals("Class", StringComparison.OrdinalIgnoreCase)) continue;
if (wordsCount > index + 1) continue;
if (words[index + 1].Equals("Class", StringComparison.OrdinalIgnoreCase)) continue;
yield return words[index + 1];
}
}

find and extract a number from a string 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 3 years ago.
Improve this question
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
"O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000"
extract :
1.2275000
2.3060000
3.3260000
....
It would be :
string temp = yourText;
List<int> numbers = new List<int>();
Regex re = new Regex(#"\d+");
Match m = re.Match(temp);
while (m.Success)
{
numbers.Add(Convert.ToInt32(m.Value));
temp = temp.Substring(m.Index + m.Length);
m = re.Match(temp);
}
First of all, you mentioned "from these strings", though you gave a single string. I am not clear about this part.
Secondly, what do you mean by extract? Do you want to find the position of a number in the string? If yes then you can simply use string search as following
string str = "O:2275000 BF:3060000 D:3260000";
int index = str.IndexOf("3060000");
if (index != -1)
{
Console.WriteLine(index);
}
else
{
Console.WriteLine("Not Found");
}
Or if the problem is stated like that: you were given a string and you want to extract the numbers out of it, then you can do it like so:
List<decimal> findNumbers(string str)
{
List<decimal> x = new List<decimal>();
string tokens = "";
foreach (char ch in str)
{
if (Char.IsNumber(ch))
{
tokens = tokens + ch;
}
if (!Char.IsNumber(ch) && !String.IsNullOrEmpty(tokens))
{
decimal num = Convert.ToDecimal(tokens);
x.Add(Convert.ToDecimal(num));
tokens = "";
}
}
if (String.IsNullOrEmpty(tokens))
{
x.Add(Convert.ToDecimal(tokens));
}
return x;
}
this function returns the list of numbers available in the string.
We can try using string split here:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
foreach (string n in numbers)
{
Console.WriteLine(n);
}
This prints:
2275000
3060000
3260000
You can do this in a single line with Linq.
string numbers = "O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000";
List<int> list = numbers.Split(' ').Select(x => Convert.ToInt32(string.Concat(x.Where(Char.IsDigit)))).ToList();
Tim Biegeleisen's answer is correct except it does not produce floating point output as you mentioned in your question. In his answere, just replace foreach loop with for statement, like this:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0}.{1}", i+1, numbers[i]);
}

Categories

Resources