0

C# newbie...(again) Slowly getting used to String class (and everything else!) Wondering how to manipulate chars like a char[] array

My code below -

    private void sendString(String stringToSend)
    {
        for(int p=0; p < stringToSend.Length; p++)
        {
            // I want to select individual characters from stringToSend
            Console.Write(stringToSend);  **<< XX HERE ? XX**
            // followed by an inter-character delay
        }
    }

Of course, this works for the whole string. but I only want to send one charater at a time with a delay between chars. TIA

1
  • 2
    Just to be clear, you cannot manipulate individual chars in a string. In C#, strings are immutable, meaning that they cannot be changed after created. You can retrieve the individual chars using indexers (array notation), but you will need to convert the string to a char array if you want to manipulate them. Commented Dec 17, 2016 at 11:00

2 Answers 2

3

You can use the string's indexer to access its individual characters, like this:

private void sendString(String stringToSend)
{
    for(int p=0; p < stringToSend.Length; p++)
    {
        Console.Write(stringToSend[p]);
        Thread.Sleep(10);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

They just call toString like this ComPort.Write(stringToSend[p].toString()) @MC
Magic - thanks! C++ had all those meaningless colons, C# replaced them with meaningful () pairs!
1

First solution is to use of indexer

 private void sendString(String stringToSend)
{
    for(int p=0; p < stringToSend.Length; p++)
    {
        Console.Write(stringToSend[p]);
        //delay code syntax here

    }
}

And second solution is to use ToCharArray function to convert string to character array.

    private void sendString(String stringToSend)
{
    char[] sendchar = stringToSend.ToCharArray();
            foreach (char item in sendchar)
            {
                Console.Write(item);
                //delay here
            }
}

But it's better to use first solution.Because that will simply iterate over string and using ToCharArray()will allocate new memory(Extra).

2 Comments

The ToCharArray is redundant. You can just as easily use a foreach on the string itself.
Yes using ToCharArray() is a bit overhead also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.