Array.IndexOf ... ? RRS feed

  • Question

  • I have a program where I want to read the content of a string after an ! and before <CR><LF> (carriage return, line feed). All string will contain these 3 amongst others and each will occur only once.

    I understand that it can't be done directly from a string so following MSDN I placed the string into a character array.
    array<Char>^ rxData = rxString->ToCharArray();
    To get the index of the ! I thought to use Array.IndexOf but I can't seem to get it to work. I tried to identify the problem by simplifying by just trying to display the index in a textbox

    this->serAddr2->Text = Convert::ToString(Array::IndexOf(rxData,"!"));
    This consistently gives me -1 which is saying that the value is not there. So I tried to simplify further.
    this->serAddr2->Text = Convert::ToString(rxData[3]);
    But this always gives me 0. I fear that my issue is incompatibility between data types (e.g. Char, char, int, Int16, Byte). Whatever the case, why can't I index anything and how to I find the index of a value? I've even tried my own function to no avail

    private: System::Int16 FindIndex(String^ totalString){
    	int i;
    	array<Char>^ strConv = totalString->ToCharArray();
    	for (i = 0; i < strConv->Length; i++){
    		if(strConv->GetValue(i)== 0)
    		return i;
    	return -1;
    Help is really appreciated.
    Wednesday, July 8, 2009 6:51 AM


All replies

  • You made a simple mistake. Your array contains characters not strings so IndexOf(rxData, "!") returns -1 you should try IndexOf(rxData, '!'). (Use single quote instead of double quote to have ! charachter instead of one length string !)

    Mohammadreza Jooyandeh
    Wednesday, July 8, 2009 7:40 AM
  • BTW: Why don't you use String.Substring and String.IndexOf on the string object instead of converting it to character array?
    Something like:
        this->serAddr2->Text = rxString->Substring(rxString->IndexOf('!') /*+ 1*/);

    Wednesday, July 8, 2009 2:51 PM
  • Thanks guys. I new it was something simple... maybe not that simple. I may end up using substrings so I don't have to spend so much time converting back in to strings for display.
    Thursday, July 9, 2009 11:30 PM