8

How do I split a string into an array of characters in C#?

Example String word used is "robot".

The program should print out:

r
o
b
o
t

The orginal code snippet:

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


namespace Testing
{
class Program
{
    static void Main(string[] args)
    {
        String word = "robot";

        String[] token = word.Split(); // Something should be placed into the () to 
        //print letter by letter??

        foreach (String r in token)
        {
            Console.WriteLine(r);
        }
    }
}
}

How can the codes be correctly implemented?

JavaNoob
  • 3,494
  • 19
  • 49
  • 61
  • 7
    Your use of the word 'alphabet' where most would write 'letter' is potentially very confusing. – High Performance Mark Nov 22 '10 at 15:15
  • I think your question makes more sense if you replace `alphabet` with `letter`. Is that the word you wanted? – Nobody Nov 22 '10 at 15:15
  • What do you mean, 'print alphabet by alphabet'? – George Stocker Nov 22 '10 at 15:16
  • 1
    What do you mean by 'tokenize'? You've been asked several times and have yet to provide any feedback. Until you do so, you're likely going to keep end up getting the same solutions. Help us help you! – Bob G Nov 22 '10 at 15:23
  • @rmx Yes its letters/alphabets. – JavaNoob Nov 22 '10 at 15:27
  • @ Michael No its not. Im just exploring other ways to do the method. – JavaNoob Nov 22 '10 at 15:27
  • @Dark By tokenizing I was wondering if there is a method to use the "split" class to seperate each letters from the word. – JavaNoob Nov 22 '10 at 15:28
  • @JavaNoob "Codes" is somewhat inaccurate, it's source 'code'. – George Stocker Nov 22 '10 at 15:54
  • Dunno what's so hard about this guys. In the Java world you used to split strings using the StringTokenizer: http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html. Even in it's first iteration it was obvious what the OP was asking... – Kev Nov 22 '10 at 15:55
  • @Kev The thing is, in the C# world (and in the C and C++ world) it's a lot easier to split a string apart. No need to use a special class for it. – George Stocker Nov 22 '10 at 15:56
  • @george - yes I know...in fact even in Java world they have String.Split but it uses regex instead. but I'm just pointing out that OP is using a valid terminology and that it isn't being misused as per your tweet. – Kev Nov 22 '10 at 16:03
  • @kev see "Alphabet" vice "Letter". That was the cause of the confusion. – George Stocker Nov 22 '10 at 16:06
  • @george - even though the code was a dead give away..and OP looks like a non-english speaker so possibly 'alphabet' -> 'letter' was lost in translation. And tokenise is a fair enough general term for splitting a string. – Kev Nov 22 '10 at 16:12
  • possible duplicate of [Does C# have a String Tokenizer like Java's?](http://stackoverflow.com/questions/70405/does-c-have-a-string-tokenizer-like-javas) – Kev Nov 22 '10 at 16:35
  • @Kev not really, the example he gives is a single word; whereas the other question is asking about words in a sentence. – George Stocker Nov 22 '10 at 17:07
  • @To everyone whom have a problem with the word Alphabet: The question was posed in Alphabets in the first place due to the meaning of other characters rather than just plain english check it out "Letter (alphabet), a written element of an alphabet that represents a single phoneme" . If you were also wondering who would use the Alphabets word please check the British Dictionary. – JavaNoob Nov 23 '10 at 06:00

6 Answers6

18

Why not this?

public void WriteLetters(string s)
{
    foreach (char c in s)
    {
        Console.WriteLine(c); 
    }
}

If you really want to see it in an explicit character array, do the following:

string s = "robot";
char[] charArray = s.ToCharArray();

If you then want to print that out (1 per line), do the following:

for (int i = 0; i < charArray.Length; i++)
{
    Console.WriteLine(charArray[i]);
}

I'm not really sure what you're trying to do, so I may be way off base.

If by tokenize, you mean store the characters in an array, you already have that in a String object1.

1 Not actually true, because String uses an indexer to iterate through the character values, whereas in C/C++, a string is actually an array of characters. For our purposes, we can treat a string as if it is an array of characters

George Stocker
  • 57,289
  • 29
  • 176
  • 237
12

The class String implements IEnumerable<char> and therefore to run through the letters of a string, you can just grab an IEnumerator<char> and process the chars one at a time. One way to do this is using a foreach:

foreach(char c in "robot") {
    Console.WriteLine(c);
}

If you need each char in an array you can just use String.ToCharArray:

char[] letters = "robot".ToCharArray();
jason
  • 236,483
  • 35
  • 423
  • 525
  • Any way of tokenizing the word? – JavaNoob Nov 22 '10 at 15:17
  • 4
    @JavaNoob: What does that mean to you? – jason Nov 22 '10 at 15:18
  • @Jason If possible I do not want to use a loop to sperate the word. And I need each alphabet in an array. – JavaNoob Nov 22 '10 at 15:25
  • 1
    @JavaNoob Ok, first off, it's letters/characters. Not alphabets. That doesn't really make any sense, and it's confusing, so use the proper word. Second, you HAVE to use a loop. The Split() function is implemented using a loop, so whether you know it or not a loop is occurring in your code. If you *really* want, you could move the loop into a separate function and have it build and return a `char[]` so you don't have to see it in your Main, but that's about all you can do. – Spencer Hakim Nov 22 '10 at 15:35
  • @spartan: You can use `word.ToCharArray()` - see my answer below. – Nobody Nov 22 '10 at 15:38
  • @rmx Wow, I appear to have a case of the Mondays, really should've remembered that exists. Fail. – Spencer Hakim Nov 22 '10 at 15:42
  • Haha don't worry, I did the exact same thing in my answer and then edited it. – Nobody Nov 22 '10 at 15:43
  • @JavaNoob: To get the `char` in an array you can just use `String.ToCharArray` as in `char[] letters = "robot".ToCharArray();`. – jason Nov 22 '10 at 15:47
1

Do you mean something like this?

foreach(var alpha in myString.Where(c => Char.IsLetter(c)))
{
    Console.WriteLine(alpha);
}
Matt Greer
  • 60,826
  • 17
  • 123
  • 123
1

You are trying to do too much.

Try this:

        String word = "robot";

        foreach (char letter in word)
        {
            Console.WriteLine(letter);
        }

Edit:

To split the string into character array, without a loop, you can do this: word.ToCharArray()

Nobody
  • 4,731
  • 7
  • 36
  • 65
1

You can using ToArray() method to return the char array.

string word = "robot";
char[] array = word.ToArray();
John Sloper
  • 1,813
  • 12
  • 14
  • Note that `ToArray` is an extension method to `String`, and you'll need to add `using System.Linq;` to your file. – Nobody Nov 22 '10 at 15:44
  • But why would you? string implements `IEnumerable` and for most intents and purposes can act just like a char array as is (especially with LINQ). – Matt Greer Nov 23 '10 at 21:19
1

Seems everyone wants to convert a String into an Array of Chars.

How about

for(int i = 0; i < tmpString.Length; i++)
Console.WriteLine(tmpString[i]);

Now you have the speed of a char array without the extra memory of making a copy.

edit: A String is an array of chars internally, there just isn't a way to change their values because String are immutable. But you can read from that char array. String = Read-Only char array.

I can't think of any reason to convert a String into a Char[] unless you wanted to "edit" the string.

long lTicks;
            char[] tmpChar = { 'a', 'b', 'c', 'd', 'e' };
            String tmpString = "abcde";
            char chRead;

            lTicks = DateTime.Now.Ticks;
            for (int i = 0; i < 100000000; i++)
                chRead = tmpChar[i%5];

            Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());

            lTicks = DateTime.Now.Ticks;
            for (int i = 0; i < 100000000; i++)
                chRead = tmpChar[i % 5];

            Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());

            lTicks = DateTime.Now.Ticks;
            for (int i = 0; i < 100000000; i++)
                chRead = tmpString[i%5];

            Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());

            lTicks = DateTime.Now.Ticks;
            for (int i = 0; i < 100000000; i++)
                chRead = tmpString[i % 5];

            Console.WriteLine(((DateTime.Now.Ticks - lTicks) / 10000).ToString());

            Console.ReadLine();

Kind of funny, the String is actually consistently faster than the Char[]. I ran each twice to make sure there wasn't a load time issue affecting the results. Compiled as Release with optimizations. Char[] was ~1950ms and String ~1850ms every run for me.

Bengie
  • 1,035
  • 5
  • 10
  • Everybody is doing that because that's what he wants. If we're just writing out the characters to the console, I addressed that in my answer below. – George Stocker Nov 22 '10 at 15:53
  • So is a `string` an object or an array of characters? – George Stocker Nov 22 '10 at 15:57
  • He wanted to split a string into an array of chars ,*Key part* So that hey may output the individual characters. It sounds like he didn't know you could treat a string like an array of chars, I assumed his question was to be read understanding that he doesn't know his options. – Bengie Nov 22 '10 at 16:05
  • A string is an object that stores an array of chars, but does give any methods to modify the contents of those chars. You may read from, but not update as a char[]. You can easily make your own string class and I've had to do so with C/C++. – Bengie Nov 22 '10 at 16:17