if statement: variable != list of strings

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 4080 Views - Last Post: 01 August 2012 - 02:14 PM Rate Topic: -----

#1 qwertyuu  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 31-July 12

if statement: variable != list of strings

Posted 31 July 2012 - 11:32 AM

Hi DiC, I am very new at C# programming and this is my first language ever (oh boy, here we go...)

I am currently building a Console application that constantly scans the user input and executes various tasks depending on the input.

Since it may be mixing up just to write "EXIT" to close the application, I wanted to add a list of strings, containing about 10 ways to close the program. Example: exit, close, stop... and all of those in Capital letters too, making the string list even longer. My current code looks like that (only the useful parts)
string[] closeApp = { "exit", "EXIT", "QUIT", "quit", "stop", "STOP", "close", "kill", "KILL", "CLOSE", "  " };
[...]
 else if (userValue != closeApp[0] && userValue != closeApp[1] && userValue != closeApp[2] && userValue != closeApp[3] && userValue != closeApp[4] && userValue != closeApp[5] && userValue != closeApp[6] && userValue != closeApp[7] && userValue != closeApp[8] && userValue != closeApp[9] && userValue != closeApp[10])
            {
                goto BEGIN;
            }



My question is: Is there a way to include the list of strings closeApp[0] to closeApp[10] within less characters?
Even though this code works well, I just feel like it's useless since I am 100% sure there's a shorter way to "say" this.
Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: if statement: variable != list of strings

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,465
  • Joined: 05-May 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 11:40 AM

You can use String.Compare() that takes a flag to ignore case.
http://msdn.microsof...y/zkcaxw5y.aspx

You can use a loop (for, foreach, while, do-while) to iterate over your array.
http://msdn.microsof...8).aspx#Looping

And as a side: do not use goto's. It's very poor form and encourages writing spaghetti code. There are other looping structures that can achieve what you need to do.

This post has been edited by Skydiver: 31 July 2012 - 11:44 AM

Was This Post Helpful? 3
  • +
  • -

#3 Ryano121  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1363
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Re: if statement: variable != list of strings

Posted 31 July 2012 - 11:41 AM

First of all instead of repeating each of the options in the array in lower and upper case. Just put them all in the same case. Then just convert the input to the same case using .ToLowerCase() etc. Will make your life a lot easier.

As for other problem you have a lot of options - you should never be writing all those conditionals for that type of equality. A couple of options -

1. Linear search - loop through each element of the array, if an element matches with the input then maybe return true or set a flag etc.

2. Binary search - if all elements in the array are sorted then you can use Array.BinarySearch which will give you an index of the item is present. If the result is -1 then the item is not present. A binary search will be much quicker to execute than the linear search.

You could also perhaps use the .Find method to accomplish the same thing

3. Shove all the strings into a List<string> and use list.Contains which will simply return a bool if the item is present.

Also try not to use goto statements. It will prevent us from crying inside :)

This post has been edited by Ryano121: 31 July 2012 - 11:42 AM

Was This Post Helpful? 0
  • +
  • -

#4 qwertyuu  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 31-July 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 11:43 AM

View PostSkydiver, on 31 July 2012 - 11:40 AM, said:

You can use String.Compare() that takes a flag to ignore case.
http://msdn.microsof...y/zkcaxw5y.aspx

You can use a loop (for, foreach, while, do-while) to iterate over your array.

And as a side: do not use goto's. It's very poor form and there are other looping structures that can achieve what you need to do.


I have read this... gotos are harmful. BUT! This is the only thing I could use as a beginner (very very very beginner) to make it work

As for the String.Compare, I have tried. My syntax was not right and I couldn't achieve my goal, even after an hour of searching in google.

Thanks for the quick reply, Skydiver!
Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5929
  • View blog
  • Posts: 12,851
  • Joined: 16-October 07

Re: if statement: variable != list of strings

Posted 31 July 2012 - 11:46 AM

Two things. First, forget goto. There is NEVER is valid justification to use it in C#.

Second, use methods. A lot. For your code, I'd write something like:
bool isCloseApp(string userValue) {
	string[] closeApp = { "exit", "EXIT", "QUIT", "quit", "stop", "STOP", "close", "kill", "KILL", "CLOSE", "  " };
	foreach(string s in closeApp) {
		if (s==userValue) { return true; }
	}
	return false;
}



Alternately, you could use List<string> and call the Contains method.
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,465
  • Joined: 05-May 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 11:53 AM

View Postqwertyuu, on 31 July 2012 - 11:43 AM, said:

I have read this... gotos are harmful. BUT! This is the only thing I could use as a beginner (very very very beginner) to make it work


What tutorial or book are you following? Or are you coming into C# having learned BASIC or FORTRAN first?


View Postqwertyuu, on 31 July 2012 - 11:43 AM, said:

As for the String.Compare, I have tried. My syntax was not right and I couldn't achieve my goal, even after an hour of searching in google.


You were searching for code to cut and paste. If you simply stopped and read the documentation, it even has sample code on how to use it. To quote from the documentation at: http://msdn.microsof...y/zkcaxw5y.aspx

Quote

:
Examples:
:
    // This is the effective equivalent of another Compare method, which ignores case
    Console.WriteLine("The Strings are equal when capitalized ? " +
        (String.Compare(szAsciiUpper, szAsciiLower, true)==0?"true":"false") );


Was This Post Helpful? 0
  • +
  • -

#7 qwertyuu  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 31-July 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 11:55 AM

For the GOTOs: I'll try... As I said, it's the only method I "understand and master" at the very moment, and this is why I came here. I came to learn how to write codes well and how to code at a base.

For the loops: I don't really master this kind of code yet (I don't understand a single thing of what you guys just said, haha), so instead of asking you guys how to write a code from the base, I think I'll go on with my basic lessons.

Thanks Again for the very quick answers!
Was This Post Helpful? 0
  • +
  • -

#8 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,465
  • Joined: 05-May 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 12:02 PM

View PostRyano121, on 31 July 2012 - 11:41 AM, said:

First of all instead of repeating each of the options in the array in lower and upper case. Just put them all in the same case. Then just convert the input to the same case using .ToLowerCase() etc. Will make your life a lot easier.

As for other problem you have a lot of options - you should never be writing all those conditionals for that type of equality. A couple of options -

1. Linear search - loop through each element of the array, if an element matches with the input then maybe return true or set a flag etc.

2. Binary search - if all elements in the array are sorted then you can use Array.BinarySearch which will give you an index of the item is present. If the result is -1 then the item is not present. A binary search will be much quicker to execute than the linear search.

You could also perhaps use the .Find method to accomplish the same thing

3. Shove all the strings into a List<string> and use list.Contains which will simply return a bool if the item is present.

Also try not to use goto statements. It will prevent us from crying inside :)


Don't use ToUpper() or ToLower() and then do a string comparison. Use the string compare functions with the appropriate flags instead. This will hopefully keep you from running into the Turkish I problem.

If you must choose between ToUpper() or ToLower(), choose ToUpper().

More details from MSDN about handling strings here: http://msdn.microsof...y/ms973919.aspx
Was This Post Helpful? 3
  • +
  • -

#9 qwertyuu  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 31-July 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 12:04 PM

View PostSkydiver, on 31 July 2012 - 11:53 AM, said:

What tutorial or book are you following? Or are you coming into C# having learned BASIC or FORTRAN first?


As I stated in the OP, I did not learn ANY codes before. Some very basic Python (about 100 pages of a book I got at the library), and that's about it.
The lessons I am following are those: http://channel9.msdn...olute-Beginners

Since I just cannot go on watching the next episode of the tutorials, I'm creeping on google trying to find answers to my very idiotic questions and now I just feel bad about asking such questions so early in here.

View PostSkydiver, on 31 July 2012 - 11:53 AM, said:

You were searching for code to cut and paste. If you simply stopped and read the documentation, it even has sample code on how to use it. To quote from the documentation at: http://msdn.microsof...y/zkcaxw5y.aspx


I was searching for a very well explained thing, where I could find my way easily... also, the string.Contains line made me wonder, because I clearly need (or do I?) a != in my code (or any other "does not equal to" syntax) so the program skips the block if I did not write an EXIT input. I may sound wrong, and I am very sorry about this.

Thanks!
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3662
  • View blog
  • Posts: 11,465
  • Joined: 05-May 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 12:14 PM

Don't feel bad about asking questions. Often though, in the process of forming the question, we learn things along the way and end up answering out own question, and move on to a harder one instead. Such is life. :lol:

This site has some pretty good tutorials. Also at the top of the C# forum are some recommendations for books and other resources as well.
http://www.dreaminco...dated-2011-8-8/

This post has been edited by Skydiver: 31 July 2012 - 12:14 PM

Was This Post Helpful? 0
  • +
  • -

#11 qwertyuu  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 31-July 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 01:31 PM

View Postbaavgai, on 31 July 2012 - 11:46 AM, said:

Two things. First, forget goto. There is NEVER is valid justification to use it in C#.

Second, use methods. A lot. For your code, I'd write something like:
bool isCloseApp(string userValue) {
	string[] closeApp = { "exit", "EXIT", "QUIT", "quit", "stop", "STOP", "close", "kill", "KILL", "CLOSE", "  " };
	foreach(string s in closeApp) {
		if (s==userValue) { return true; }
	}
	return false;
}



Alternately, you could use List<string> and call the Contains method.


After a little of mess-around and a lot of goole with the "return true;" or return anything... The Compiler tells me that my program returns void so "a return keyword must not be followed by an object expression"

What's the matter?
I'm also getting better at bypassing GOTOs, yay! :sweatdrop:
Was This Post Helpful? 0
  • +
  • -

#12 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4576
  • View blog
  • Posts: 8,018
  • Joined: 08-June 10

Re: if statement: variable != list of strings

Posted 31 July 2012 - 01:44 PM

You're going to have to post your updated code for us to know. The error means exactly what it says: a void method can't return a value. But that doesn't really help much, since you don't know what a method is, apparently. So post your code and we'll show you where, that'll help.

I hate to be a wet blanket, but it's pretty clear you need to start from scratch. Get yourself a book, or find a complete beginner web series, and start there. I mean, how did you even find goto? Whatever taught you that is just plain wrong, and I suggest you stop using it as a resource. Learn how to use methods (functions) properly, which a beginner C# book will teach you.
Was This Post Helpful? 0
  • +
  • -

#13 qwertyuu  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 31-July 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 02:00 PM

Curtis:
I'm learning from there
http://channel9.msdn...olute-Beginners

But you know... Internet bandwidth limits and steam sales aren't great friends, so I'm stuck at the end of my month trying to use as less bandwidth possible. I found myself creating a simple application with what I learned from the series.

I learned the goto in my past years, messing around in different very small codes such as batch and TexasInstrument TI-84Plus BASIC.

For no reason, I knew there was a way to go back to another line of code and my subconsciousness stored it as goto. Having a little search around in google revealed me that goto was usable in C#, so I used it... as simple as this.

The purpose of my application is to fake an "application debugger" in which I can write a password that will start an hidden process in the computer. Anyway, let's get to the code itself:

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace startexe
{
    class Program
    {
        static void Main(string[] args)
        {
        RESET:
            string[] closeApp = { "exit", "EXIT", "QUIT", "quit", "stop", "close", "kill", "KILL", "CLOSE", "STOP", "  " };
            Console.WriteLine("C# Syntax Debugger 1.7 BUILD 33");
            Console.WriteLine("");
        BEGIN:
            Console.Write("C:/>");
            string userValue = Console.ReadLine();
            if (userValue == "PASSWORD")
            {
                Process.Start("C:/Program Files/application/application.exe");
                Console.Clear();
                goto RESET;
            }
            else if (userValue == "")
            {
                Console.WriteLine("You wrote nothing. Please type HELP for help. (Error #443)");
                goto BEGIN;
            }

            else if (userValue == "HELP" || userValue == "help" || userValue == "Help")
            {
                Console.WriteLine("Type a debug syntax or EXIT to close the debugger.");
                goto BEGIN;
            }

            else if (userValue != closeApp[0] && userValue != closeApp[1] && userValue != closeApp[2] && userValue != closeApp[3] && userValue != closeApp[4] && userValue != closeApp[5] && userValue != closeApp[6] && userValue != closeApp[7] && userValue != closeApp[8] && userValue != closeApp[9])
            {
                Console.WriteLine("'{0}' is not a known syntax. Please type HELP for help. (Error #5)", userValue);
                goto BEGIN;
            }
        }
    }
}



very simple question regarding the forum... how does one edit a post?

( :offtopic: )
Was This Post Helpful? 0
  • +
  • -

#14 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4576
  • View blog
  • Posts: 8,018
  • Joined: 08-June 10

Re: if statement: variable != list of strings

Posted 31 July 2012 - 02:01 PM

Two tutorials that you need to read:

Methods
Control Structures (focus on the section about loops, specifically the do-while loop).

Then, you can ditch your labels and gotos, and start learning modern (as in, newer than 1980's) programming.

Quote

very simple question regarding the forum... how does one edit a post?


Answer: you don't, until you have a certain number of posts. We've had too many people edit out their entire question and code after they get their answer, so we stopped letting people edit. If there's some change you need to make, post it as a reply in the thread.
Was This Post Helpful? 1
  • +
  • -

#15 qwertyuu  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 31-July 12

Re: if statement: variable != list of strings

Posted 31 July 2012 - 02:05 PM

Thanks alot Curtis

Also, digging that profile pic. Made me laugh!

Quote

Answer: you don't, until you have a certain number of posts.


Thanks, since a whole lot of forum just bans you when you doublepost, I was wondering before being banned myself.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2