Sinaesthetic
Sinaesthetic

Reputation: 41

C#: Split a string (or user input) into individual characters withOUT using an array?

Ok here's what im trying to do. The user is prompted to enter an 8 digit number (7 numbers plus a hyphen

781-0432

I want it to break it apart and store it into 8 separate char variables without using an array:

a = 7 b = 8 c = 1 ... h = 2

Ive been trying to do it with the Console.Read() method:

a = Console.Read(); b = Console.Read(); etc

Problem is, i don't know how to key the Console.Read() to stop reading after that. If the module is contained in a loop, it seems to not reset on the next call.

I know what you're thinking. Why the hell would you not use an array or the split to char array option? Well because it is a homework assignment that is very specific on it wants you to accomplish it. This is the first one to stump me in a while. Any insight?

Upvotes: 1

Views: 2805

Answers (3)

Chase Florell
Chase Florell

Reputation: 47387

what about storing your characters in a POCO that you can retrieve later?

public void SomeEvent()
{
    string PhoneNumber = "781-0432"
    Alphabet alphabet = SplitNumber(PhoneNumber);
    // Pass the alphabet object around and maintain the individual characters!
}

public Alphabet SplitNumber(string number)
{
    Alphabet alphabet = new Alphabet();
    alphabet.a = number[0];
    alphabet.b = number[1];
    alphabet.c = number[2];
    alphabet.d = number[3];
    alphabet.e = number[4];
    alphabet.f = number[5];
    alphabet.g = number[6];
    alphabet.h = number[7];
    return alphabet;
}

class Alphabet
{
    public string a;
    public string b;
    public string c;
    public string d;
    public string e;
    public string f;
    public string g;
    public string h;
}

Now you can move Alphabet around your app and maintain the individual characters.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415850

public char ReadChar()
{
   char r = ' ';
   while (r < '0' || r > '9')
      r = Console.ReadKey();
   return r;
}

a = ReadChar();
b = ReadChar();
//...

Upvotes: 1

Callum Rogers
Callum Rogers

Reputation: 15829

It already is an Array (well, sort of*)!

You can access each individual character by using an indexer on the string. For example:

string str = "781-0432"; // To take input, you can use Console.ReadLine()
char firstChar = str[0];
char secondChar = str[1];
// etc

*Technically a string is not an array, but it has a custom indexer that lets it be used like a char[].

Upvotes: 3

Related Questions