Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string can be made by chars of another string in C#

Tags:

string

c#

.net

How to check, if a word can be made by letters of another word. using every letter only once.

Example:

if str = "computer"; then

//if user enters below words output must be true
  comp
  put
  poet

//and if user enters below words output must be false
  count         // since n is not in str 
  root          // since there is only single o in str    
like image 862
Javed Akram Avatar asked Apr 02 '11 05:04

Javed Akram


People also ask

How do you check if a string contains a character from another string?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do you check if a string matches another string in C?

We take the user input as strings. We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

How do you check if a certain character is in a string in C?

The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search.


2 Answers

This is a solution based on counting the number of each character and then checking that the second word has fewer of each character:

public static bool UsesSameLetters(string input, string check)
{
    var OriginalCounts = input.GroupBy(c => c)
        .ToDictionary(g => g.Key, g => g.Count());
    bool Success = check.GroupBy(c => c)
        .All(originalCounts.ContainsKey(g.Key) 
            && originalCounts[g.Key] >= g.Count);
    return Success;
}

This solution counts the number of each character in the input string, and then checks if every character in the check string occurs less times than it does in the input string. This solution is fairly declaritive.

like image 122
Chris Pitman Avatar answered Oct 23 '22 09:10

Chris Pitman


The following should do the trick

public static bool UsesSameLetters(string input, string check) {
  var array = new BitArray(check.Length, false);
  for (var i = 0; i < input.Length; i++) {   
    var found = false;
    for (var j = 0; j < check.Length; j++) {
      if (input[i] == check[j] && !array.Get(j)) {
        array.Set(j, true);
        found = true;
        break;
      }
    }
    if (!found) {
      return false;
    }
  }
  return true;
}
like image 38
JaredPar Avatar answered Oct 23 '22 09:10

JaredPar