# string to char...

## Recommended Posts

pascalosti    100
Can someone tell me how to get single characters from a string to a char array. This book by deitel is driving me crazy. Its asking for a struct but the book doesnt use one. It has to be in .NET .
void EnterName(){
String ^x;
String ^tmp, ^y;

for(int i = x->Length; i > 0; i--){
y =  String::Concat(tmp,x->Chars[i].ToString());}

Console::WriteLine(" {0}",y);
}

Error	1	error C3293: 'Chars': use 'default' to access the default property (indexer) for class 'System::String'	c:\Documents and Settings\posti\Desktop\String Assignment\String\String\String.cpp	15
Error	2	error C2228: left of '.ToString' must have class/struct/union	c:\Documents and Settings\posti\Desktop\String Assignment\String\String\String.cpp	15



##### Share on other sites
T_Janssen    138
the error tells you, you should use indexing to get the character from the Chars property

in code:

x[i]

returns a character at position i

another thing:
in the for loop, you start at i=x->Length
note that indexing starts at 0 and ends at Length-1, so you're trying to get a character beyond the length of the string.

##### Share on other sites
pascalosti    100
thank you that worked, the stuff from before is right out of a book, I have to stop buying cheap drugs...

void EnterName(){
String ^x;
String ^tmp, ^y;
int counter = 0;

Console::WriteLine(" size {0}", x->Length);
for(int i = x->Length; i > 0; i--){

Console::Write("{0}", y = String::Concat(tmp,x[counter].ToString()));
counter++;}

Console::WriteLine(" The result:{0}",x);
}