d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > C++ Extracting Chars From A String
Add Reply New Topic New Poll
Member
Posts: 19,256
Joined: Mar 24 2008
Gold: 710.00
Apr 8 2015 09:14am
Long story short, what would be the most efficient way to extract chars from a string.

Lets say my string is "1 + 99 - ( 10 * 2 )"

how would I extra each character ['1' ,'+' ,'99' ,'-' ,'(' ,'10' ,'*' ,'2' ,')' ] while skipping the spaces.
I will be putting those chars into a char dyanmic array, so char_dynamic_array[0] would be '1', char_dynamic_array[1] will be '+', and so on.
Member
Posts: 13,425
Joined: Sep 29 2007
Gold: 0.00
Warn: 20%
Apr 8 2015 12:17pm
Code
std::string myWord = "myWord";
char myArray[myWord.size()+1];//as 1 char space for null is also required
strcpy(myArray, myWord.c_str());


You will need to parse out the spaces yourself with a regex or string replace function.

I would use the string iterator and string erase method to do this.

Code
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());


The first finds all locations of space, and the second deletes them all until the end of the string.
Member
Posts: 19,256
Joined: Mar 24 2008
Gold: 710.00
Apr 8 2015 02:15pm
i dont think that solves the problem. Correct me if im wrong, but that code just deletes all of the spaces, and makes a new string without the spaces.
then im assuming i would make a for loop and assign array[iterator]= string[iterator], to fill the string into the array, but it wouldnt be able to support 2 digit numbers , like 10, and 99.

What i need is to get the first digit '1' from the string, store that into a char array[0], so i assume some type of string to char conversion has to go down.
skip the space
char '+' store it in array[1]
skip the space
char '99' store it in array[2]
skip the space
char '-' store it in array [3]
skip the space
etc, till all of the chars excluding the spaces are in the array.

that array of chars is going to be analyzed to see if the array[iterator]is going to be a number, operator, or a parenthesis, then go through other processing.

This post was edited by Pino38 on Apr 8 2015 02:18pm
Member
Posts: 13,425
Joined: Sep 29 2007
Gold: 0.00
Warn: 20%
Apr 8 2015 02:22pm
The second code block removed all spaces.
The first converts the string into a C string (character array).
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll