Conversion of character code for a letter to a string containing the letter itself in MSVC - string

MSVC 2015 CLI: I used the following code to convert the unicode for the letter A (i.e. decimal 65) into a string containing the letter itself:
int i = 65;
char c = (char)(i);
return c.ToString();
The string returned is not "A" but "65"
To resolve, I had to use the std string, i.e.
int i = 65;
char c = (char)(i);
std::string MyStdString = &c;
String^ d = gcnew String(MyStdString.c_str());
return d;
The string returned is "A"
There must be a way to solve this without the second approach. Although this solved my issue, I would be grateful for help on syntax for the first approach, and to understand why it won't work as it is.

You are mixing between char and Char(Note Capital C).
Following code should give you expected result:
int i = 65;
Char c = i;
Console::WriteLine(c.ToString());

Related

Which character to append to string in suffix array?

I was solving
https://www.spoj.com/problems/BEADS/
above question at SPOJ. I have stated the relevant information below:
Problem Statement:
The description of the necklace is a string A = a1a2 ... am specifying sizes of the particular beads, where the last character am is considered to precede character a1 in circular fashion.
The disjoint point i is said to be worse than the disjoint point j if and only if the string aiai+1 ... ana1 ... ai-1 is lexicografically smaller than the string ajaj+1 ... ana1 ... aj-1. String a1a2 ... an is lexicografically smaller than the string b1b2 ... bn if and only if there exists an integer i, i <= n, so that aj=bj, for each j, 1 <= j < i and ai < bi.
Output:
For each test case, print exactly one line containing only one integer -- number of the bead which is the first at the worst possible disjoining, i.e. such i, that the string A[i] is lexicographically smallest among all the n possible disjoinings of a necklace. If there are more than one solution, print the one with the lowest i.
Now the solution is using SUFFIX ARRAY. Input string s, and concat with itself, s'=s+s ,since I have to sort cyclic suffixes of array. Then create a suffix array on s', and output the smallest index that points to a suffix of original s, i.e., index < len(s).
But there is a problem I face. I was appending '$' character to get SA, but I was getting wrong answer. After looking online, I found 1 solution that had appended '}' to string.
I found that ascii('$') < ascii('a') < ascii('z') < ascii('}')
But i don't understand how this will make a difference, why this is accepted answer and haven;t found a case where this will make a difference. The solution (AC) can be found here:
Link to Code
#include <bits/stdc++.h>
using namespace std;
string s;int n;
bool cmp_init(int a, int b)
{
return s[a]<s[b] || (s[a]==s[b] && a<b);
}
int jmp;
vector<int> pos;
bool cmp(int a, int b)
{
return pos[a]<pos[b] || (pos[a]==pos[b] && pos[(a+jmp)%n]<pos[(b+jmp)%n]);
}
int main() {
int tc;cin>>tc;
while(tc--){
cin>>s;
int m=s.size();
s=s+s+"{";
n=s.size();
vector<int> SA(n,0);
for(int i=0;i<n;i++)SA[i]=i;
sort(SA.begin(), SA.end(), cmp_init);
pos.assign(n,0);
for(int i=1 , c=0;i<n;i++)pos[SA[i]]=(s[SA[i]]==s[SA[i-1]])?c:++c;
for(jmp=1;jmp<=n;jmp*=2)
{
sort(SA.begin(), SA.end(), cmp);
vector<int> tmp(n,0);
for(int i=1 , c=0;i<n;i++)tmp[SA[i]]=(pos[SA[i]]==pos[SA[i-1]] && pos[(SA[i]+jmp)%n]==pos[(SA[i-1]+jmp)%n])?c:++c;
for(int i=0;i<n;i++)pos[i]=tmp[i];
}
for(int i=0;i<n;i++)if(SA[i]<m){cout<<SA[i]+1<<"\n";break;}
}
}
PS.: I have found that SA construction code is correct, only problem is with last character appending. Normally we append '$' in SA construction.
The difference is in the last condition:
If there are more than one solution, print the one with the lowest i.
Consider input "abab".
The correct answer is 0, which you get when you append '}', because "abababab}" is less than all of its suffixes.
If you append '$', you get the wrong answer, because "ab$" < "abab$" < "ababab$" < "abababab$".

CS50 substitution - Loop not working for length of plaintext

I am trying to create a loop for the length of the plaintext and converting the plaintext to alphabetic index so that i can get a pointer to the same location in argv[].However the loop only seems to be running for plain[0] and only getting the equivalent key for argv[0] (which is the key). Any help would be much appreciated.
string plain = get_string("plaintext: ");//prompt user for text
printf("ciphertext: ");
int lenp = strlen(plain);//get length of text
int c;
char* p;
for (int q = 0; q < lenp; q++)
{
if (isalpha(plain[q]))
{
if (isupper(plain[q]))
{
//covert from ASCII to alpabetic index
h = plain[q] - 65;
//pointer to the equivalent element in argv[]
p = &argv[1][h];
*p = argv[1][h];
c = *p;

Error in using indexOf not finding char in Arduino String

I have some code that I have no clue why it isn't working.
The code takes a serial input in the form of "xxx,yyy,zzz", where digits can range from 1 to 3 in each number. Because of an odd quirk in an app, it needs to be read as a char, then converted to a string to be handled. The intention is to split into 3 ints, red green and blue, from "RRR,GGG,BBB".
Now this works fine when I manually define String str (see commented code), but when I go and enter it from the serial console, it doesn't want to work. It seems to be coming from the indexOf(',') part, as while using Serial.print(c1);, I found that when I manually entered a string, it returned an index of the comma, but when I used the serial console, it returned -1 (not found).
And yes, the entered string into the console is in the correct format of "RRR,GGG,BBB", I've confirmed that by printing both phone and str independently.
while (Serial.available() > 0) {
char phone = Serial.read();
String str = String(phone);
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
Edit: With the Arduino String class, creating a string from a char is returning more than just one character, eleven in fact.
This:
char phone = Serial.read();
String str = String(phone);
will never create a string in str that has more than 1 character, since that's what you say you want.
This is the code for the Arduino's String(char) constructor:
String::String(char c)
{
init();
char buf[2];
buf[0] = c;
buf[1] = 0;
*this = buf;
}
So clearly your code will create a 1-character long string.
Also, beware of using indexes computed on the full string, on substrings later.
I'm try to guess that you are using these serial API http://playground.arduino.cc/Interfacing/CPPWindows.
while (Serial.available() > 0) {
char buf[12];
int len = Serial.ReadData(buf,11);
String str = String(buf);
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
If you are using other API like http://arduino.cc/en/Serial/Read you should follow these API where Serial is a Stream and read() return just the first available char.
Code was fixed by using a different function.
while (Serial.available() > 0) {
char phone = Serial.read();
str += phone;
//String str = "87,189,183";
int ln = str.length()-1;
int c1 = str.indexOf(','); //first place to cut string
int c2 = str.indexOf(',',c1+1); //second place
red = str.substring(0,c1).toInt();
green = str.substring(c1,c2).toInt();
blue = str.substring(c2,ln).toInt();
Serial.print(red);
I'm not sure why this works, and why before I was getting a string with more than one character. But it works!

How to count two characters in a string?

There are three parameters (String s, char c, char d)
How do I define a method so that it returns as an int, the number of times the char c occurs in the String s added to the number of times the char d occurs in the String s?
Depending on the language, there could already be an existing function that does this for you.
Otherwise, you'd need to treat the string like an array (if the language does that, then great. If it doesn't, then you need to cast it into an array), run a loop and use a counter. If you want to look for specific characters, you can pass that in a function along with the string/array).
Example (this is just psudo-code, since I don't know what language you're using):
function countCharsInString(string s, char c1, char c2)
{
int count = 0;
for(i = 0; i < s.Length; i++)
{
if(s[i] == c1 || s[i] == c2)
{
count++;
}
}
return count;
}

stick integer to string and char*

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;

Resources