detect the first character in a variable c#
I have a program that reads in serial information from a device and that works fine but i want to make a statement something like; if (first character = R) do something if (first character = T) do something else
I hope this makes sense. Basically all i need to do is have a way to detect the f开发者_运维百科irst character from a variable, then remove that character from the variable.
Thanks
Assuming we are talking about a string:
string input = GetInput();
string remainingPart = input.Substring(1); // get string without first character
switch (input[0])
{
case 'R':
{
DoSomething(remainingPart);
break;
}
case 'T':
{
DoSomethingElse(remainingPart);
break;
}
// more case clauses follow here
default:
{
break;
}
}
Is it a string variable? Then you can easily access it's first character:
string mystring = ...
if (!String.IsNullOrEmpty(mystring))
{
char first = mystring[0];
// ...
string withoutFirst = mystring.Substring(1);
// ...
}
String.StartsWith()
: Determines whether the beginning of this string instance matches the specified string.
String.Substring()
: Retrieves a substring from this instance. The substring starts at a specified character position.
If you need to read char and discard it, then I suggest that it is better for you to use Queue.
First, split the string into characters and queue it into a Queue. And then dequeue each item in the queue and process it as required.
精彩评论