I want to make A to 1, ... , Z to 26.
My code can make A to 1, but it can't make J -> 10 , ... , Z -> 26. Please tell me how to change mine.
void changeToDigitEncode(char s[], char e[]) {
int i;
int eIndex = 0;
for (i = 0; s[i] != '\0'; i++) {
e[eIndex] = s[i]-'A'+'0'+1;
eIndex++;
}
e[eIndex] = '\0';
}
int main(void) {
char sentence[20], encoded[40];
scanf("%s", sentence);
changeToDigitEncode(sentence, encoded);
printf("%s\n", encoded);
}
Normally you can do this:
int a_lower = 'a' - 'a' + 1; // value : 1
int j_lower = 'j' - 'a' + 1; // value : 10
For capitals, a similar thing:
int a_upper = 'A' - 'A' + 1; // value : 1
int j_upper = 'J' - 'A' + 1; // value : 10
As a comment pointed out, You can't store most integers as a single character. Whereas a character array element is a single character. So, instead you will have to create an integer array and store the values there.
Plus, it would be s[i]-'A'+ 1 simply
Another thing I added is a termination condition for the encoded array which would be number 0 as no alphabet will give number 0.
#include <stdio.h>
void changeToDigitEncode(char s[], int e[]) {
int i;
int eIndex = 0;
for (i = 0; s[i] != '\0'; i++) {
e[eIndex] = s[i]-'A'+1;
eIndex++;
}
e[eIndex] = 0;
}
int main(void) {
char sentence[20];
int encoded[20];
scanf("%s", sentence);
changeToDigitEncode(sentence, encoded);
for(int i=0; encoded[i]!=0; i++) {
printf("%d ",encoded[i]);
}
}
try this code consider ip[] as your s[] and op[] as your e[]
char ip[] = "ABC";
char op[3];
char temp[50];
int i=0;
int j=0;
int k=0;
while(ip[i]!='\0')
{
int num=ip[i];
num-=64;
sprintf(temp, "%d", num);
k=0;
while(temp[k]!='\0')
{
op[j++]=temp[k++];
}
i++;
}
op[i]='\0';
printf("-->%s\n",op);
this will only work for String in Caps
Related
I'm very new to C and trying to create a counter for how many times the letter "a" appears in a string. I get it working by putting it directly into main, however when I put it into a function, my printf outputs 0.
#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 50
void letter_counter(char input[STRING_LENGTH], int count, char letter ) {
int i;
for (i = 0; i < strlen(input); i++){
if (input[i] == letter) {
count++;
}
}
}
int main() {
int a1 = 0;
char a = 'a';
printf("Please write a word\n");
char input[STRING_LENGTH] = {0};
fgets(input,STRING_LENGTH,stdin);
input[strlen(input) - 1] = 0;
letter_counter(input, a1, a);
printf("%i\n", a1);
}
You are not returning the value of what you have counted. It looks like you think that a1 is going to contain the total, but it's not.
Your letter_counter function needs to return an int value, not void.
int letter_counter(char input[STRING_LENGTH], char letter ) {
int i;
int count = 0;
for (i = 0; i < strlen(input); i++){
if (input[i] == letter) {
count++;
}
return count;
}
Then you need to assign the return value of the function to a variable:
a1 = letter_counter(input, a);
Given some number in a form of string, I want to extract every k-th number from it. Then I go through the remaining string and extract every k-th number again. The thing I get as a result should be the number formed by these extracted ones(in a proper order). Example: 123456789, k = 3 --> 369485271
My algorithm is as follows: While the lenght of the string allows extracting every k-th number, I go through the string and store every k-th element in another string. Then I delete the extracted elements from the original string by tracking the proper index of an element and proceed forvard while the lenght of my str is sufficient.
I can't figure out what's the problem with my code. And maybe my approach isn't that good and there are some better/simpler ways of diong this?
#include <stdio.h>
#include <string.h>
void remove(char *str, unsigned int index) {
char *src;
for (src = str+index; *src != '\0'; *src = *(src+1),++src) ;
*src = '\0';
}
int main() {
char number[100];
char result[100];
int k;
printf("Enter a string: ");
scanf("%s",number);
printf("Enter a key: ");
scanf("%d",&k);
while (strlen(number)>k-1) {
for (int i = 0, p = 0; number[i] != '\0'; i++) {
if (i % k == (k-1)) {
result[p] = number[i];
p++;
}
}
for (int j = 0; number[j] != '\0'; j++){
if (j % k == (k-1)) {
remove(number, j);
j+=1; /*since the index was shifted due to removing an element*/
}
}
}
puts(result);
return 0;
}
You some issues:
You start writing your output from scratch again in each iteration of your while loop.
You do not handle the last digits
You do not treat the input as a cyclic input.
You do not terminate your output string.
remove is already a name of standard library function.
A shorter version could be this (untested):
#include <stdio.h>
#include <string.h>
void remove_digit(char *str, unsigned int index) {
char *src;
for (src = str+index; *src != '\0'; *src = *(src+1),++src)
;
}
int main() {
char number[100];
char result[100];
int k;
printf("Enter a string: ");
scanf("%s",number);
printf("Enter a key: ");
scanf("%d",&k);
int p = 0;
int i = 0;
int skip = k-1; // We remove 1 digit and skip k-1 digits
while (number[0] != 0) {
i = (i + skip) % strlen(number);
result[p] = number[i];
p++;
remove_digit(number, i);
}
number[p] = 0;
puts(result);
return 0;
}
The following code seems to be what you want:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void remove_(char *str, unsigned int index) {
char *src;
for (src = str+index; *src != '\0'; *src = *(src+1),++src) ;
*src = '\0';
}
int main(int argc, const char * argv[]) {
char number[100];
char result[100];
int tmp[100];
int k;
printf("Enter a string: ");
scanf("%s",number);
printf("Enter a key: ");
scanf("%d",&k);
int p = 0;
for (int tp = 0; strlen(number) > k-1; tp = 0) {
for (int i = 0; number[i] != '\0'; i++)
if (i % k == (k-1))result[p++] = number[i];
for (int j = 0; number[j] != '\0'; j++)
if (j % k == (k-1)) tmp[tp++] = j;
for (; tp; --tp) remove_(number, tmp[tp-1]);
}
// The newly added code
for (int index; strlen(number); ) {
index = (k-1) % strlen(number);
result[p++] = number[index];
remove_(number, index);
}
puts(result);
return 0;
}
The most important thing is that every while loop, you need to remove the elements in number at once. While ensuring the integrity of your original code, I made some changes. Unfortunately, the main idea of the original code is wrong.
It should circulate from the tail (including the rest) to the head after one round. But I found that the function of the code you provided is that after each round, the next round starts from the 0th element of the head.
By the way, your algorithm is similar to the Josephus problem
As the title says %s is not working properly This is for a code wars so %s needs to be able to work with the array to pass the sample test cases; Cannot change function declaration of playPass. Using Ascii table. Also the for loop to print in main() works and gives me correct output.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// takes a string and shifts letter n value;
// lower cases every other element if it contains a letter
// replaces number with a 9 complement
// returns array with values reversed.
char* playPass(char* s, int n)
{
int length = strlen(s);
char *pass= (char *)malloc(length*sizeof(char)+1);
char a;
int letter, i;
for(i=0; i< length; i++)
{
a = s[i];
letter = a;
if( letter >= 65 && letter <=90 )
{
letter +=n;
if(letter >90)
{
letter -=90;
letter +=64;
}
if((i+1) % 2 == 0 )
{
letter += 32;
}
a = letter;
}
else if(letter >= 48 && letter <= 57)
{
letter -= 48;
letter = 9 - letter;
a = letter + '0';
}
pass[length - i] = a;
}
return pass;
}
// answer should be
int main (){
char* s ={"I LOVE YOU!!!"};
int length = strlen(s);
int k = 1;
s =playPass( s,k );
int i;
printf(" %s", s);
for(i = 0; i <= length; i++)
{
printf(" %c", s[i]);
}
}
%s works only with null terminated char *
char* playPass(char* s, int n) {
…
for() {
…
}
pass[i] = '\0'; //Null terminate here.
return pass;
}
so figured it out.
the end where i assined the new value to the new array
pass[length - i] = a;
made it to where it never wrote a value to the first element so
pass[0]= NULL;
had to change it to
pass[length - (i-1)] = a;
thanks for the help everyone, I also cleaned up the code from the magic numbers Great tip #phuclv!
I am doing this programming problem where I have reverse string of about 30 characters for 10 test cases.
My code is this:-
#include <stdio.h>
#include <string.h>
int main () {
int t;
scanf("%d",&t);
while (t--) {
char str[30];
scanf("%s",&str);
char revStr[30];
int len = strlen(str);
int i = 0;
int j = len-1;
while (i < len) {
revStr[i] = str[j];
i++; j--;
}
printf("%s\n",revStr);
}
return 0;
}
The output gets garbled up if the input string is larger than previous string.
For example,
if last-string had 6 characters, like rocket\0 and new-string, which is fun\0 has 3 characters, the output is funket\0.
char str[30];
scanf("%s",&str);
^ don't pass address of array
Just this would work -
scanf("%29s",str);
Try this:
int t;
scanf("%d", &t);
while (t--)
{
char str[30] = { 0 };
scanf("%s", &str);
char revStr[30] = { 0 };
int len = strlen(str);
int i = 0;
int j = len - 1;
while (i < len) {
revStr[i] = str[j];
i++; j--;
}
printf("%s\n", revStr);
}
You need to make two changes
Firstly change scanf("%s",&str); to
scanf("%s",str);
Secondly, after the while loop, you are not making the last element rev string \0. Add this line before the printf statement.
revStr[i] = '\0';
This should solve your problem.
I know that getline is C++ standard but I need to read a line of digits:
123856
and save it to an array. But how to do this without spaces between given (as input) digits? I want a user input to be:
123856 (with no spaces) and then save it to an array (n element array) and after that, I want my array to look like this:
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 8;
array[4] = 5;
array[5] = 6;
But how to make it in C, without a getline?
This is NOT what I want:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char **argv)
{
int t[4];
int i;
for(i=0; i<4; i++)
scanf("%d", &t[i]);
for(i=0; i<4; i++)
printf("%d\n", t[i]);
return 0;
}
If I understood you correct, the following should do it:
read the whole line
loop through the string as long as you get digits or the string ends
for every digit, place it's value in your array and increase the index by 1
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
/* If desired, add check for value outside of 0-9 */
array[ i++ ] = c - '0';
...
}
char arr[] = "1234567";
int intarr[10];
int count = 0;
for (char* ptr = arr; *ptr; ptr++) {
intarr[count] = *ptr - '0';
count++;
}
try this
#include <stdio.h>
#include <string.h>
main (int argc, char *argv[])
{
FILE *f;
int i=0;
int j=0;
char output[100];
char* output1[100];
char string[100];
char delims1[] = " ";
char delims2[] = "*";
char* result = NULL;
char* result3 = NULL;
int num;
//for (j=0; j<2; j++)
//{
//printf("%s",delims9[6]);
//}
f = fopen("text.txt","r");
//
while( fgets(string,sizeof(string),f) )
{
result = strtok( string, delims1 );
while( result != NULL )
{
output1[i]=result;
printf("%s\n",output1[i]);
result = strtok( NULL, delims1 );
i++;
}
for (num = 0; num < 100; i++ ) //
{ // Error On this array
printf("%s\n", output1[i]); //
} //
}
printf("\n%d",i/3+1);
return 0 ;
}
Ok, without using any string.
int digits = 123856;
int numofdigits = 1 + floor(log10(digits));
int digits_arr[numofdigits];
int i;
for(i = numofdigits-1; i >= 0; i--) {
digits_arr[i] = (int)floor(digits / pow(10, i)) % 10;
}
Try the below link... Same question asked here and get solution....
convert an integer number into an array
char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}