I want to take different length strings without knowing their length and distributing their characters in arrays as input in c++.
Take number of strings (3)
Take first string. Example: hello and it should be saved like
a[]={'h','e','l','l','o'}
Take second string
Take third string
To store the characters of a string in an array, you could try this:
string string1 = "Hello";
char a[string1.length()+1];
for (int i = 0; i < string1.length(); i++)
{
a[i] = string1[i];
}
That will loop through the entire string and by using .length(), store the indexed values in a[]. If you have several strings, just repeat the process.
Related
I'm reading from a file a series of strings, one for each line.
The strings all have the same length.
File looks like this:
010110011101
111110010100
010000100110
010010001001
010100100011
[...]
Result : 010110000111
I'll need to compare each 1st char of every string to obtain one single string at the end.
If the majority of the nth char in the strings is 1, the result string in that index will be 1, otherwise it's going to be 0 and so on.
For reference, the example I provided should return the value shown in the code block, as the majority of the chars in the first index of all strings is 0, the second one is 1 and so on.
I'm pretty new to C++ as I'm trying to move from Web Development to Software Development.
Also, I tought about making this with vectors, but maybe there is a better way.
Thanks.
First off, you show the result of your example input should be 010110000111 but it should actually be 010110000101 instead, because the 11th column has more 0s than 1s in it.
That being said, what you are asking for is simple. Just put the strings into a std::vector, and then run a loop for each string index, running a second loop through the vector counting the number of 1s and 0s at the current string index, eg:
vector<string> vec;
// fill vec as needed...
string result(12, '\0');
for(size_t i = 0; i < 12; ++i) {
int digits[2]{};
for(const auto &str : vec) {
digits[str[i] - '0']++;
}
result[i] = (digits[1] > digits[0]) ? '1' : '0';
}
// use result as needed...
Online Demo
I'm looking to write a C++ console app that takes in lines of text from a .txt file, which I have done, now what I need to do is check each line for consecutive pairs of letters
"For example, the word “tooth” has one pair of double letters, and the word “committee” has two pairs of consecutive double letters."
Should I convert each line into a Cstring and loop through each character? I really don't know where to start with this.
I'm not looking for someone to write out the entire solution, I just need to know how to start this.
You could loop through the string from start to the second last char and compare 2 chars at a time. In C++17 you have std::string_view which is handy.
#include <string_view>
size_t pair_count(std::string_view s) {
size_t rv = 0; // the result
for(size_t idx = 0; idx < s.size() - 1; ++idx) {
// compare s[idx] and s[idx+1]
// if they are equal, increase rv by one
// and increase idx by one (if you want "aaa" to count as 1 and not 2)
}
return rv;
}
I have a stream of strings in format something like this a:b, d:a, t:w, i:r, etc. Since I keep on appending these string, in the end it becomes a very large string.
I am trying to encode, for example:
a:b -> 1
d:a -> 2
etc.
My intension is to keep the final string as small as possible to save on memory. Hence I need to give single digit value to string occuring maximum number of times.
I have following method in mind:
Create: map<string, int> - this will keep the string and its count. In the end I will replace string with maximum count with 1, next with 2 and so on till last element of map.
Currently size of final string are ~100,000 characters.
I can't compromise on speed, please suggest if anyone has better technique to achieve this.
If I understand correctly your input strings are of the range "a:a"..."z:z" and you simply need to count the appearances of each in the stream, regardless of order. If your distribution is even enough you can count them in using a uint16_t.
A map is implemented using a tree, so an array is much more efficient than a map both in memory and time.
So you can define an array
array<array<uint16_t, 26>, 26> counters = {{}};
and assuming your input is, for example input = "c:d", you can fill up the array as follows
counters[input[0]-'a'][input[2]-'a']++;
Then finally you can print out the frequencies of the input like this
for (auto i=0; i < counters.size() ; ++i) {
for (auto j=0; j < counters[i].size(); ++j) {
cout<<char(i+'a')<<":"<<char(j+'a')<<" "<<counters[i][j]<<endl;
}
}
I have a string say toioyhpknmtlghk.I want to create a 2-d character array having n rows such that it contains first,second,third sub strings of length n as it's rows.
For example,here n=5 the sub strings of length 5 are, toioy hpknm and tlghk
so array arr should look like
t o i o y
h p k n m
t l g h k
Now this could have been easier if I copy the characters by looping through the array but here I am trying to use memcpy as,
int main()
{
long n;
cin>>n;
char a[3][n+1];char str[20]; //I have taken n+1 columns as n for substring and 1 for '\0'
scanf("%s",str);
char *p=str;
memcpy(a[0],p,n);strcat(a[0],"\0");
p=p+n;
memcpy(a[1],p,n);strcat(a[1],"\0");
p=p+n;
memcpy(a[2],p,n);strcat(a[2],"\0");
for(int i=0;i<3;i++)
{
printf("%s\n",a[i]);
}
}
But on outputting the array following results are obtained,
//input
5
toioyhpknmtlghk
//output
toioy
hpknm{tlghk‼â
tlghk‼â
The command strcat(a[0],"\0"); is working on strings which are already terminated by \0. Otherwise it doesn't know where to append the second string. In your case a[0] is not terminated, so the function will induce undefined behavior. You can do the following instead:
a[0][n] = '\0';
(the same is for the rest of a elements)
i've been thinking for a long time and havent got anywhere with the program. i dont know where to begin. The assignment requires use of single function main and only iostream library to be used.
the task is to Declare a char array of 10 elements. Take input from user. Determine if array contains any values more than 1 times . do not show the characters that appears 1 time only.
Sample output:
a 2
b 4
..
a an b are characters. and 2 and 4 represents number of times they appear in the array B.
i tried to use nested loop to compare a character with all the character in array and incrementing a counter each time similer character id sound but unexpected results are occuring.
Here is the code
#include <iostream>
using namespace std;
void main()
{
char ara[10];
int counter=0;
cout<<"Enter 10 characters in an array\n";
for ( int a=0; a<10; a++)
cin>>ara[a];
for(int i=0; i<10; i++)
{
for(int j=i+1; j<10; j++)
{
if(ara[i] == ara[j])
{
counter++;
cout<<ara[i]<<"\t"<<counter<<endl;
}
}
}
}
Algorithm 2: std::map
Declare / define the container:
std::map<char, unsigned int> frequency;
Open the file
read a letter.
find the letter: frequency.find(letter)
If letter exists, increment the frequency: frequency[letter]++;
If letter no exists, insert into frequency: frequency[letter] = 1;
After all letters processed, iterate through the map displaying the letter and its frequency.
Here's one possible way you can solve this. I'm not giving you full code; it's considered bad to just give full implementations for other people's homework.
First, fill a new array with only unique characters. For example, if the input was:
abacdadeff
The new array should only have:
abcdef
That is, every character should appear only once in it. Do not forget to \0-terminate it, so that you can tell where it ends (since it can have a length smaller than 10).
Then create a new array of int (or unsigned, since you can't have negative occurrences) values that holds the frequency of occurence of every character from the unique array in the original input array. Every value should be initially 1. You can achieve this with a declaration like:
unsigned freq[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
Now, iterate over the unique array and every time you find the current character in the original input array, increment the corresponding element of the frequencies array. So at the end, for the above input, you would have:
a b c d e f (unique array)
3 1 1 2 1 2 (frequencies array)
And you're done. You can now tell how many times each characters appears in the input.
Here, I'll tell you what you should do and you code it yourself:
include headers ( stdio libs )
define main ( entry point for your app )
declare input array A[amount_of_chars_in_your_input]
write output requesting user to input
collect input
now the main part:
declare another array of unsigned shorts B[]
declare counter int i = 0
declare counter int j = 0
loop through the array A[] ( in other words i < sizeof ( A ); or a[i] != '\0' )
now loop as much as there is different letters in the array A
store the amount of letters in the B[]
print it out
Now there are some tricks applying this but you can handle it
Try this:
unsigned int frequency[26] = {0};
char letters[10];
Algorithm:
Open file / read a letter.
Search for the letters array for the new letter.
If the new letter exists: increment the frequency slot for that
letter: frequency[toupper(new_letter) - 'A']++;
If the new letter is missing, add to array and set frequency to 1.
After all letters are processed, print out the frequency array:
`cout << 'A' + index << ": " << frequency[index] << endl;