Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to compare a string and an array like this,

    string str1 = "Ceo, Hr, Coo, Mccal";
    string[] str2 = new string[] {"CEO", "COO", "HR", "McCal","CSU","PSU"};

I want to check if str2 has a value of str1, checking one value at a time, like Ceo, then Hr, then Coo etc. If there is a match, I want the str2 value, like looking up Ceo should return me CEO.

What is the most efficient way to do it without looping? I have to compare multiple strings to str2.

share|improve this question
1  
This forum is about code reviewing. Your previous question was moved here because you were asking for reviewing your code for improvements, but this one is offtopic here – almaz Jan 9 at 21:40

closed as off topic by almaz, Corbin, Glenn Rogers, palacsint, Brian Reichle Jan 10 at 8:56

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

1 Answer

You didn't specify a language, so I'll write in Java. You should be able to do the equivalent just as easily.

Java has the String.split() function, which could be used on ", " to give you a string array. From there, the problem is a variation of determining if a string is in multiple arrays. Personally, I like using a HashSet for that functionality, although there are a number of ways to do it.

Just a quick code sketch:

HashSet<String> str2Set = new HashSet<String>();
for(String s : str2)
    str2Set.add(s);

String[] splitStr1 = str1.split(", ");

for(String s : splitStr1)
   //toUpperCase may not be necessary outside example depending on your data
   if(str2Set.contains(s.toUpperCase())
      return s.toUpperCase();

EDIT 1:

C# string split:

Regex(", ").Split(str1);
share|improve this answer
I am sorry, it is C#. – user1424052 Jan 9 at 21:44
Thanks. If you notice, I need Mccal as McCal, not all uppercase. – user1424052 Jan 9 at 21:54
As a quick and dirty fix to the capitalization issue, you can use a HashMap with a toUppercase version of the string as the key. Not sure if there's a way in C# to ignore case in HashSets. – WLPhoenix Jan 9 at 22:02
I was able to do what I wanted. Unfortunately, the topic has been closed by the Admin, so I cannot post the solution code here. I did use Regular Expressions. – user1424052 Jan 10 at 20:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.