stick integer to string and char* - string

How can I add an integer variable to a string and char* variable? for example:
int a = 5;
string St1 = "Book", St2;
char *Ch1 = "Note", Ch2;
St2 = St1 + a --> Book5
Ch2 = Ch1 + a --> Note5
Thanks

The C++ way of doing this is:
std::stringstream temp;
temp << St1 << a;
std::string St2 = temp.str();
You can also do the same thing with Ch1:
std::stringstream temp;
temp << Ch1 << a;
char* Ch2 = new char[temp.str().length() + 1];
strcpy(Ch2, temp.str().c_str());

for char* you need to create another variable that is long enough for both, for instance. You can 'fix' the length of the output string to remove the chance of overrunning the end of the string. If you do that, be careful to make this large enough to hold the whole number, otherwise you might find that book+50 and book+502 both come out as book+50 (truncation).
Here's how to manually calculate the amount of memory required. This is most efficient but error-prone.
int a = 5;
char* ch1 = "Book";
int intVarSize = 11; // assumes 32-bit integer, in decimal, with possible leading -
int newStringLen = strlen(ch1) + intVarSize + 1; // 1 for the null terminator
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
snprintf(ch2, intVarSize, "%s%i", ch1, a);
ch2 now contains the combined text.
Alternatively, and slightly less tricky and also prettier (but less efficient) you can also do a 'trial run' of printf to get the required length:
int a = 5;
char* ch1 = "Book";
// do a trial run of snprintf with max length set to zero - this returns the number of bytes printed, but does not include the one byte null terminator (so add 1)
int newStringLen = 1 + snprintf(0, 0, "%s%i", ch1, a);
char* ch2 = malloc(newStringLen);
if (ch2 == 0) { exit 1; }
// do the actual printf with real parameters.
snprintf(ch2, newStringLen, "%s%i", ch1, a);
if your platform includes asprintf, then this is a lot easier, since asprintf automatically allocates the correct amount of memory for your new string.
int a = 5;
char* ch1 = "Book";
char* ch2;
asprintf(ch2, "%s%i", ch1, a);
ch2 now contains the combined text.
c++ is much less fiddly, but I'll leave that to others to describe.

You need to create another string large enough to hold the original string followed by the number (i.e. append the character corresponding to each digit of the number to this new string).

Try this out:
char *tmp = new char [ stelen(original) ];
itoa(integer,intString,10);
output = strcat(tmp,intString);
//use output string
delete [] tmp;

Related

Swap two words in a char* using constant space in less than o(n^2) time

Given a char* to a string, say containing "hellosir", and the length's of each word,
how can I return a char* containg "sirhello" using constant space in less than o(n^2) time?
(I was asked this in an tech interview)
Function signature:
char* swapWords(char* str, int firstWordLen, int secondWordLen);
In the "hellosir" example firstWordLen is 5, and secondWordLen is 3.
Thanks
char* swapWords(char* str, int firstWordLen, int secondWordLen) {
char* newStr = (char*) malloc(sizeof(char) * (firstWordLen + secondWordLen + 1));
for(int i = 0; i < secondWordLen; i++) {
newStr[i] = str[firstWordLen + i];
}
for(int i = 0; i < firstWordLen; i++) {
newStr[secondWordLen + i] = str[i];
}
newStr[firstWordLen + secondWordLen] = 0;
return newStr;
}
Explanation:
Loop over the second word, it starts at the end of word one, so firstWordLen + i, and place the chars at the beginning of the new char array
Loop over the first word, so from 0 to firstWordLen and place it at the end of the previously placed second word, so at secondWordLen + i
Add 0 to the end of the new char array because of null termination
Ah ok, this is not constant space my bad, the speed is O(n), but the space is also O(n)

String to Int Conversion in Arduino

I' am trying to convert string to int(like Integer.parseInt() in java) in arduino in order to make some operation's on the numbers. Unfortunately none of my solution's worked.
Until now I tried:
Create char Array and call atoi function:
String StringPassword;
uint8_t *hash;
//Here I define hash
int j;
for (j = 0; j < 20; ++j) {
StringPassword.concat(hash[j]);
}
//Checking String Size
Serial.println("Size");
//Checking String
Serial.println(StringPassword.length());
Serial.println(StringPassword);
int jj;
char PasswordCharArray[StringPassword.length()];
StringPassword.toCharArray(PasswordCharArray, StringPassword.length());
awa = atoi(PasswordCharArray);
Serial.println(awa);
Output:
Size
48
168179819314217391617011617743249832108225513297
18209
Create char Array for null terminated string and call atoi function:
String StringPassword;
uint8_t *hash;
//Here I define hash
int j;
for (j = 0; j < 20; ++j) {
StringPassword.concat(hash[j]);
}
//Checking String Size
Serial.println("Size");
//Checking String
Serial.println(StringPassword.length());
Serial.println(StringPassword);
int jj;
char PasswordCharArray[StringPassword.length()+1];
StringPassword.toCharArray(PasswordCharArray,StringPassword.length()+1);
awa = atoi(PasswordCharArray);
Serial.println(awa);
Output:
Size
48
168179819314217391617011617743249832108225513297
-14511
use toInt Function:
String StringPassword;
uint8_t *hash;
//Here I define hash
int j;
for (j = 0; j < 20; ++j) {
StringPassword.concat(hash[j]);
}
//Checking String Size
Serial.println("Size");
//Checking String
Serial.println(StringPassword.length());
Serial.println(StringPassword);
awa = StringPassword.toInt();
Serial.println(awa);
Output:
Size
48
168179819314217391617011617743249832108225513297
-14511
What is the proper way of changing String to Int so:
awa = 168179819314217391617011617743249832108225513297 ?
And could someone explain to me why my solution's didn't worked? I tried to use the function's that were mentioned on Stackoverflow and Arduino forum to solve this.
The number 168179819314217391617011617743249832108225513297 reaches the maximum integer value limit so therefore this will not convert into an integer.
Try using atol() instead of atoi(). Long numbers can hold more data like the number shown above.

garbage in loop for no reason

i wrote a function that receives a string as a char array and converts it to an int:
int makeNumFromString(char Str[])
{
int num = 0, len = 0;
int p;
len = strlen(Str);
for (p = 0; p<len; p++)
{
num = num * 10 + (Str[p] - 48);
}
return num;
}
the problem is that no matter how long the string i input is, when "p" gets to 10 the value of "num" turns to garbage!!!
i tried debbuging and checking the function outside of the larger code but no success.
what could be the problem and how can i fix it?
THANKS
Perhaps your int can only store 32 bits, so the number cannot be higher than 2,147,483,647.
Try using a type for num with more storage, like long.

Reduce a string when it has a pair

Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.
Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!
If the final string is empty, print Empty String; otherwise, print the final non-reducible string.
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0: Shil can perform the following sequence of operations to get the final string:
Thus, we print .
Sample Case 1: Shil can perform the following sequence of operations to get the final string: aaabccddd -> abccddd
abccddd -> abddd
abddd -> abd
Thus we print abd
Sample case 1: baab -> bb
bb -> Empty String.
in my code in the while loop when i assign s[i] to str[i].the value of s[i] is not getting assigned to str[i].the str[i] has a garbage value.
my code :
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string s;
cin>>s;
int len = s.length();
int len1 = 0;
string str;
for(int i = 0;i < len-1;i++){
if(s[i]!= '*'){
for(int j=i+1;j < len;j++){
if(s[j] != '*'){
if(s[i] == s[j]){
s[i] = s[j] = '*';
}
}
}
}
}
int i = 0;
while(i<len){
if(s[i] != '*'){
str[len1] = s[i];
len1++;
}
i++;
}
if(len1 != 0){
cout<<str;
}
else{
cout<<"Empty String";
}
return 0;
}
#include <iostream>
using namespace std;
int main(){
string s,tempS;
bool condition = false;
cin >> s;
tempS = s;
while(condition==false){
for(int i=1; i<s.size(); i++){
if(s[i]==s[i-1]){
s.erase(s.begin()+i-1, s.begin()+i+1);
}
}
if(tempS == s){
condition = true;
} else{
tempS = s;
}
}
if(s.size()==0){
cout << "Empty String" ;
} else{
cout << s;
}
return 0;
}
the first while loop keeps on modifying the string until and unless it becomes equal to temp (which is equal to the string pre-modification)
It is comparing the adjacent elements if they are equal or not and then deleting them both.
As soon as string becomes equal to temp after modifications, string has reached it's most reduced state !

Converting a 1D pointer array (char) into a 2D pointer array (char) in Visual C++.

I am new to c++ programming I have to call a function with following arguments.
int Start (int argc, char **argv).
When I try to call the above function with the code below I get run time exceptions. Can some one help me out in resolving the above problem.
char * filename=NULL;
char **Argument1=NULL;
int Argument=0;
int j = 0;
int k = 0;
int i=0;
int Arg()
{
filename = "Globuss -dc bird.jpg\0";
for(i=0;filename[i]!=NULL;i++)
{
if ((const char *)filename[i]!=" ")
{
Argument1[j][k++] = NULL; // Here I get An unhandled
// exception of type
//'System.NullReferenceException'
// occurred
j++;
k=0;
}
else
{
(const char )Argument1[j][k] = filename [j]; // Here I also i get exception
k++;
Argument++;
}
}
Argument ++;
return 0;
}
Start (Argument,Argument1);
Two things:
char **Argument1=NULL;
This is pointer to pointer, You need to allocate it with some space in memory.
*Argument1 = new char[10];
for(i=0, i<10; ++i) Argument[i] = new char();
Don't forget to delete in the same style.
You appear to have no allocated any memory to you arrays, you just have a NULL pointer
char * filename=NULL;
char **Argument1=NULL;
int Argument=0;
int j = 0;
int k = 0;
int i=0;
int Arg()
{
filename = "Globuss -dc bird.jpg\0";
//I dont' know why you have 2D here, you are going to need to allocate
//sizes for both parts of the 2D array
**Argument1 = new char *[TotalFileNames];
for(int x = 0; x < TotalFileNames; x++)
Argument1[x] = new char[SIZE_OF_WHAT_YOU_NEED];
for(i=0;filename[i]!=NULL;i++)
{
if ((const char *)filename[i]!=" ")
{
Argument1[j][k++] = NULL; // Here I get An unhandled
// exception of type
//'System.NullReferenceException'
// occurred
j++;
k=0;
}
else
{
(const char )Argument1[j][k] = filename [j]; // Here I also i get exception
k++;
Argument++;
}
}
Argument ++;
return 0;
}
The first thing you have to do is to find the number of the strings you will have. Thats easy done with something like:
int len = strlen(filename);
int numwords = 1;
for(i = 0; i < len; i++) {
if(filename[i] == ' ') {
numwords++;
// eating up all spaces to not count following ' '
// dont checking if i exceeds len, because it will auto-stop at '\0'
while(filename[i] == ' ') i++;
}
}
In the above code i assume there will be at least one word in the filename (i.e. it wont be an empty string).
Now you can allocate memory for Argument1.
Argument1 = new char *[numwords];
After that you have two options:
use strtok (http://www.cplusplus.com/reference/clibrary/cstring/strtok/)
implement your function to split a string
That can be done like this:
int i,cur,last;
for(i = last = cur = 0; cur < len; cur++) {
while(filename[last] == ' ') { // last should never be ' '
last++;
}
if(filename[cur] == ' ') {
if(last < cur) {
Argument1[i] = new char[cur-last+1]; // +1 for string termination '\0'
strncpy(Argument1[i], &filename[last], cur-last);
last = cur;
}
}
}
The above code is not optimized, i just tried to make it as easy as possible to understand.
I also did not test it, but it should work. Assumptions i made:
string is null terminated
there is at least 1 word in the string.
Also whenever im referring to a string, i mean a char array :P
Some mistakes i noticed in your code:
in c/c++ " " is a pointer to a const char array which contains a space.
If you compare it with another " " you will compare the pointers to them. They may (and probably will) be different. Use strcmp (http://www.cplusplus.com/reference/clibrary/cstring/strcmp/) for that.
You should learn how to allocate dynamically memory. In c you can do it with malloc, in c++ with malloc and new (better use new instead of malloc).
Hope i helped!
PS if there is an error in my code tell me and ill fix it.

Resources