TuturuJones
TuturuJones

Reputation: 13

Using Only the First Letter in a String Stored in an Array

I'm currently writing a "Pseudo Assembly Compiler" for the MC68HC11, it's nothing complex. The issue I'm having is after reading from a file and storing into an array.

For example, I have the line "LDAA #$45", I'm first saving "LDAA" into a string array and "#$45" into a second string array. I use the first array as is, but for the second one I only need to know what the first letter or symbol in that array is so I can know what if statement I need to end up in.

The code for going into LDAA would be something like this:

if(code[i]=="LDAA"){ //code is my array for the first word read.
  if(number[i]=="#"){ //Here's where I would only need to read the first symbol stored in the array.
    opcode[i]="86";
  }
}

The code I'm using for reading from a file is similar to that found in Reading a file into an array?

I'm not sure if this is exactly possible as I can't find anything like it online.

Upvotes: 1

Views: 2191

Answers (2)

JBentley
JBentley

Reputation: 6260

You've tagged this C++, so I'm going to assume your array contains std::strings, in which case:

#include <string>
#include <iostream>

int main()
{
    std::string foo = "#$45";
    std::string firstLetter = foo.substr(0, 1);
    std::cout << firstLetter;
    return 0;
}

Produces output:

#

Is that what you were looking for? Applying to your code:

if(code[i]=="LDAA"){
  if(number[i].substr(0, 1)=="#"){
    opcode[i]="86";
  }
}

Upvotes: 0

Keith
Keith

Reputation: 6834

Depending on the type of number, you want either:

if(number[i]=='#'){ 

or

if( number[i][0]=='#'){ 

Also, are code[i], opcode[i] of type std::string or char*. [ Hopefully the former.]

Upvotes: 1

Related Questions