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?
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.
In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.
Way 1: Using a Naive Approach Get the string. Create a character array of the same length as of string. Traverse over the string to copy character at the i'th index of string to i'th index in the array. Return or perform the operation on the character array.
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
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 char
s 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With