Get the value from string vecotr and store in another string? - string

I am trying to store the string value into vector. And then after storing I want to store in string one by one. In first step split the sting by "," and store into vector. And again try to retrive and get into string.
My code:
CString sAssocVal = "test1, test2, test3";
istringstream ss( sAssocVal.GetBuffer(sAssocVal.GetLength()) );
vector<string> words;
string token;
while( std::getline(ss, token, ',') )
{
words.push_back( token );
}
Try to again retrive from vector:
for(int i = 0; i<words.size(); i++)
std::string st= words[i];
But the value of st is getting NULL always.
where I am missing some thing.

AFAIK the problem is the istringstream initialization, a small modification makes your example work:
http://coliru.stacked-crooked.com/a/698818655cbba4e7
You could first convert CString to std::string, there are a lot of topics about that problem

I resolved this is by using this code.
CString st;
for(int i = 0; i<words.size(); i++)
st= words[i].c_str();

Related

How to copy a character from basic string into a vector string?

//Defining the class
class Hangman
{
private:
vector<string> dictionary; //stores all the words
vector<string> secretWord; //stores the secret word
vector<string> misses; //keeps record of wrong guesses
vector<string> displayVector; //Stores "_"
string originalWord; //stores a copy of secret word to display at the
end of game.
bool gameOver = false; //Flag to check if the player lost or
still in the game.
int totalAttempts;
public:
void selectRandWord();
};
//This is the function i am having problem in.
void Hangman::selectRandWord()
{
secretWord.clear();
//word is a basic string that stores a random word. lets say "Hello World".
string word;
srand(time(NULL));
int random = (rand() % dictionary.size()) + 1;
//I store a random word from vector to word.
word = dictionary[random];
transform(word.begin(), word.end(), word.begin(), ::tolower);
originalWord = word;
for (int index = 0; index < word.length(); index++)
{
//This line has the error: [Error] invalid user-defined conversion from 'char' to 'std::vectorstd::basic_string<char >::value_type&& {aka std::basic_string&&}' [-fpermissive]
//What I am trying to do is take each character from word(for example: "H") and push it back into the vector string secretWord.
secretWord.push_back(word[index]);
}
}
Your secretWord is now a vector<string> type, so it's a collection of possibly many words, I'm not sure if that's what you really intend to have judging by the name. If it indeed is ok and you want to store every single character from word as a separate string in secretWord, then you need to replace push_back call with emplace_back call as the other method actually does two things at a time: constructs a string from the char you pass to it and appends the string to the end of the container, like this
secretWord.emplace_back(1, word[index]);
Mere push_back fails because it needs to be provided with an object of the type your vector stores, so you could also solve your problem by explicitly constructing a string from your char:
secretWord.push_back(string(1, word[index]));
I suggest you give a read to these: emplace back reference and push back reference if you're interested in copy/move details.

Converting hex values within a string to their string equivalent

So, I've been looking around SO and a few other sites for a solid method of converting hex values embedded in normal strings (eg. The '/' are in the string as '\x2F') and wasn't able to find a solution that specifically fit my needs.
What I ended up doing was writing a bit of code myself to handle this:
for (int i = 0; i < 128; i++)
{
string hexString = i.ToString("X").PadLeft(2, '0');
string searchString = #"\x" + hexString;
if (response.Contains(searchString))
{
int charValue = Convert.ToInt32(hexString, 16);
string character = Char.ConvertFromUtf32(charValue);
response = response.Replace(searchString, character);
}
}
My question is this:
Is this a good way of going about it?
Any perticular drawbacks to me using this?
The purpose of this code is to take a string like:
"previous content...http:\x2F\x2Fwww.google.com...after content"
and convert it to:
"previous content...http://www.google.com...after content"

Comparing a string in a struct with a string in an array

I have an array of structs, one of the elements in the struct is a string, and i need to compare those strings with other strings in an array of 12 strings. strcmp does not seem to work for me. I know i need to make seperate function to compare the the strings and return the value as a bool, but cant figure out how to make the compare function work.
The struct
typedef struct{
char *hometeam[Max_number_of_chars], *awayteam[Max_number_of_chars];
int playround, date_day, date_month, date_year,
time_hour, time_minute, home_score, away_score, crowd_thousand,
crowd_hundred;
} match;
The array of strings
char *teams[Number_of_teams] = {"AGF","AAB","SDR","RFC",
"EFB","BIF","SIF","OB",
"FCK","FCM", "ACH","FCN"};
the line where i need the compare_function
if(compare_names(all_games[i].hometeam, teams[j])==0) {//crazy stuff}
EDIT: What i need help with is making function that compares the string value from *teams[j] with the string value from all_games[i].hometeam. But i dont know how to pass the specific part of the struct all_games[i].hometeam to the compare_function, where i want it to be a char string.
// Assuming char *teams[Number_of_teams] is globally defined.
int find_match(struct match)
{
for(i=0; i < Number_of_teams; i++){
if(strcmpi(match.hometeam, teams[i]) == 0){
return i;
}
}
return -1;
}
The logical flow of what you want to do isn't clear, but you can try something like above.

Remove single character occurrence from String

I want an algorithm to remove all occurrences of a given character from a string in O(n) complexity or lower? (It should be INPLACE editing original string only)
eg.
String="aadecabaaab";
removeCharacter='a'
Output:"decbb"
Enjoy algo:
j = 0
for i in length(a):
if a[i] != symbol:
a[j] = a[i]
j = j + 1
finalize:
length(a) = j
You can't do it in place with a String because it's immutable, but here's an O(n) algorithm to do it in place with a char[]:
char[] chars = "aadecabaaab".toCharArray();
char removeCharacter = 'a';
int next = 0;
for (int cur = 0; cur < chars.length; ++cur) {
if (chars[cur] != removeCharacter) {
chars[next++] = chars[cur];
}
}
// chars[0] through chars[4] will have {d, e, c, b, b} and next will be 5
System.out.println(new String(chars, 0, next));
Strictly speaking, you can't remove anything from a String because the String class is immutable. But you can construct another String that has all characters from the original String except for the "character to remove".
Create a StringBuilder. Loop through all characters in the original String. If the current character is not the character to remove, then append it to the StringBuilder. After the loop ends, convert the StringBuilder to a String.
Yep. In a linear time, iterate over String, check using .charAt() if this is a removeCharacter, don't copy it to new String. If no, copy. That's it.
This probably shouldn't have the "java" tag since in Java, a String is immutable and you can't edit it in place. For a more general case, if you have an array of characters (in any programming language) and you want to modify the array "in place" without creating another array, it's easy enough to do with two indexes. One goes through every character in the array, and the other starts at the beginning and is incremented only when you see a character that isn't removeCharacter. Since I assume this is a homework assignment, I'll leave it at that and let you figure out the details.
import java.util.*;
import java.io.*;
public class removeA{
public static void main(String[] args){
String text = "This is a test string! Wow abcdefg.";
System.out.println(text.replaceAll("a",""));
}
}
Use a hash table to hold the data you want to remove. log N complexity.
std::string toRemove = "ad";
std::map<char, int> table;
size_t maxR = toRemove.size();
for (size_t n = 0; n < maxR; ++n)
{
table[toRemove[n]] = 0;
}
Then parse the whole string and remove when you get a hit (thestring is an array):
size_t counter = 0;
while(thestring[counter] != 0)
{
std::map<char,int>::iterator iter = table.find(thestring[counter]);
if (iter == table.end()) // we found a valid character!
{
++counter;
}
else
{
// move the data - dont increment counter
memcpy(&thestring[counter], &thestring[counter+1], max-counter);
// dont increment counter
}
}
EDIT: I hope this is not a technical test or something like that. =S

clistbox gettext error

I am trying to add items from alistbox to cstringarray. But text is null always. plz suggest the changes
int count = m_OutList.GetCount();
for ( i = 0; i <m_OutList.GetCount(); i++)
{
m_OutList.GetText( buf[i], text );
m_selcomponents->Add(text);
// getb //Add();
}
If text is a CString in your example, you need to write m_OutList.GetText(i,text) - you don't need a buffer variable if you pass a CString&. buf[i] is a part of your buffer and has a random value.

Resources