What's wrong with my code? I'm trying to count the numbers in a string after skipping all alphabets.
How to skip the alphabets and only count the numbers?
#include <stdio.h>
#include <stdlib.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if(a[i]>='a'&&a[i]<='z')
{
continue;
}
else
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[100001];
scanf("%s",a);
function(a);
printf("\n");
}
}
I switched your usage of scanf to use fgets. This works:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if (isdigit(a[i]))
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t = 0;
scanf("%d", &t);
while(t--)
{
char a[100001];
fgets(a, sizeof(a), stdin);
function(a);
puts("\n");
}
}
If the OP's intent was in fact to count up the groups of digits (in which the definition of 'number' is each contiguous run of digits), this will accomplish the goal:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int function(char a[])
{
size_t i = 0;
int cnt = 0;
// convert all non-digits to whitespace
printf("Converting\n");
for (char *p = a; *p != '\0'; ++p)
{
*p = isdigit(*p) ? *p : ' ';
}
printf("Found Groups: %s\n",a);
// note: strtok mutates the string it is given, it will not be usable after this:
for (char *gr = strtok(a," "); gr != NULL; gr = strtok(NULL, " "))
{
cnt++;
}
printf("Number of Groups: %d\n", cnt);
}
int main()
{
printf("Enter strings (Ctrl-C to end)\n");
while(1)
{
int result = 0;
char a[100001];
scanf("%s",a);
result = function(a);
printf("\n");
}
}
(I was not able to get the version using fgets to work, but how the string is gathered is not really in the scope of the question, the OP's original code in main is functional, I just made it an open-ended loop for my tests)
In your code continue statement is responsible for wrong answer. Because of it your code is not encountering the statement a[i] !='\0'. so suggest you to just avoid it and close your if statement without any code as like me. One more suggestion use also uppercase letters as user can also enter uppercase letters and using fgets() function you can also read white spaces.
Try out this
#include <stdio.h>
#include <stdlib.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if((a[i]>='a'&&a[i]<='z') || (a[i]>='A'&&a[i]<='Z'));
else
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[100001];
scanf("%s",a);
function(a);
printf("\n");
}
}
Related
Hi, how can i write a code in C that checks a string for palindromes, and then rewrites them?
For example: string> "awbiue abdba aebto leoel", should return "abdba leoel".
I wrote this code, but it can only find that the string is palindrome or not:
#include<stdlib.h>
#include<string.h>
int main()
{
char str[100];
printf("Enter string: ");
gets(str);
int f=1;
{
for(int i=0;i<strlen(str); i++)
{
if(str[i]!=str[strlen(str)-i-1])
{
f=0; break;
}
}
if(f==1)
printf("Palindrom");
else
printf("Not Palindrom");}
return 0;
}
You only need to read string by string, making sure whether they are palindrome, and if so, print them out -- that is what I did in the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[100];
printf("Enter string: ");
while(scanf("%s", str) == 1) { // read strings one by one in the str variable
//your code part
int f=1;
for(int i=0;i<strlen(str); i++)
{
if(str[i]!=str[strlen(str)-i-1])
{
f=0; break;
}
}
if(f==1) // that means that string is palindrome
printf("%s ", str); // print the string and a space
}
return 0;
}
I'm in the middle of homework and I need some help here.
So this is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int upper=0,lower=0,number = 0;
char ch[500];
printf("Enter the String:\n");
gets(ch);
i=0;
while(ch[i]!=0)
{
if(ch[i]>='A' && ch[i]<='Z')
{
upper++;
}
else if(ch[i]>='a' && ch[i]<='z')
{
lower++;
}
else if(ch[i]>='0' && ch[i]<='9')
{
number++;
}
i++;
}
printf("lowercase letters: %d",lower);
printf("\nuppercase letters: %d",upper);
printf("\nnumber letters: %d",number);
getch();
return 0;
}
As you can see here. When you give a string input. The code will give a total number of uppercase,lowercase and number
for example: If I'm giving "Hello World 123" To the code. The result will be 2 Uppercases 8 Lowercases and 3 Numbers
The problem is the task want me to print all 3 types of letter seperately
for example: from "Hello World 123" Should print "HW" , "elloorld" and "123"
I know that I have to create another 3 arrays for seperate the letter. I tried to create like upperc[i],lowerc[i] and num[i] to input the letter in each of if command but It doesn't work.
So how can I do that?
Here's one way of going about it. It doesn't require 3 separate arrays like you thought because it prints the characters directly:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
printf("Enter a string: ");
char str[1024] = {0};
fgets(str, sizeof str, stdin);
// Use different functions in each iteration
int (*ctype_fns[])(int) = {isupper, islower, isdigit};
for (unsigned i = 0; i < sizeof ctype_fns / sizeof *ctype_fns; ++i)
{
for (const char *it = str; *it; ++it)
{
// If char matches requirements, print it
if (ctype_fns[i]((unsigned char)*it))
putchar(*it);
}
putchar('\n');
}
}
Example of running:
Enter a string: Hello World 123
HW
elloorld
123
For your simple homework project you must assume some decent values. We assume the input is no longer than 128 characters and each of the three types is no more than 64. In real life projects we must check on these values.
Adapting your main, the following would work:
#include <stdio.h>
#include <stdlib.h>
#define MAX_IN 128
#define MAX_X 64
int main()
{
int i;
int upper=0,lower=0,number = 0;
char ch[MAX_IN], chUpper[MAX_X], chLower[MAX_X], chNumber[MAX_X];
printf("Enter the String:\n");
gets(ch);
i=0;
while(ch[i]!=0)
{
if(ch[i]>='A' && ch[i]<='Z')
{
chUpper[upper++]= ch[i];
}
else if(ch[i]>='a' && ch[i]<='z')
{
chLower[lower++]= ch[i];
}
else if(ch[i]>='0' && ch[i]<='9')
{
chNumber[number++]= i;
}
i++;
}
chLower[lower]= '\0';
chUpper[upper]= '\0';
chNumer[number]= '\0';
printf("lowercase letters: %d: %s\n",lower, chLower);
printf("uppercase letters: %d: %s\n",upper, chUpper);
printf("number letters: %d: %s\n",number, chNumber);
getch();
return 0;
}
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_IN 128
#define MAX_X 64
int main()
{
int i;
int upper=0,lower=0,number = 0;
char ch[MAX_IN], chUpper[MAX_X], chLower[MAX_X], chNumber[MAX_X];
printf("Enter the String:\n");
gets(ch);
printf("input given is : %s\n",ch);
for (i=0;ch[i]!='\0';i++)
{
if(ch[i]>='A' && ch[i]<='Z')
{
chUpper[upper++]= ch[i];
}
else if(ch[i]>='a' && ch[i]<='z')
{
chLower[lower++]= ch[i];
}
else if(ch[i]>='0' && ch[i]<='9')
{
chNumber[number++]= ch[i];
}
if ((ch[i+1]) == ' '){
i += 1;
}
}
printf("lowercase letters: %d: %s\n",lower, chLower);
printf("uppercase letters: %d: %s\n",upper, chUpper);
printf("number letters: %d: %s\n",number, chNumber);
return 0;
}
It prints the characters in reverse order just fine except when the string is 8 characters long.
Eg -
"what man" gives "am tahw" Why ?
whereas "what many" gives "ynam tahw" just as it should.
#include <stdio.h>
int main(void)
{
char a[100];
char x;
char*i = a;
printf("Enter a message:");
while ((x = getchar()) != '\n')
{
*i = x;
i++;
}
while (i >= &a[0])
{
printf("%c", *i--);
}
printf ("\n");
}
Modification in your code:
Change printf("%c", *i--); to printf("%c", *--i); in while loop.
You can improve the quality of your program as shown below:
#include <stdio.h>
#include <conio.h>
void main()
{
char *s;
int len,i;
clrscr();
printf("\nENTER A STRING: ");
gets(s);
len=strlen(s);
printf("\nTHE REVERSE OF THE STRING IS:");
for(i=len;i>=0;i--)
printf("%c",*(s+i));
getch();
}
Do anybody knows how to search for a name in a string array? If i register the name 'jacob' and search for cob I need to get jacob shown instead of not showing up anything. I don't know if strcmp is the right way to do it. Any ideas?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
struct name{
char name[MAX];
};
void getRegister(struct name name[], int *nrNames);
void getSearch(struct name name[], int nrNames);
int readLine(char s[], int length);
int main(){
int run=1;
struct name name[MAX];
int nrNames=0;
while(run){
char choice;
printf("\n (1)Register\n(2)Search\n(3)Quit\n");
scanf(" %c%*c", &choice);
if(choice=='1') getRegister(name, &nrNames);
if(choice=='2') getSearch(name, nrNames);
if(choice=='3') run=0;
}
return 0;
}
void getRegister(struct name name[], int *nrNames){
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
(*nrNames)++;
}
void getSearch(struct name name[], int nrNames){
int i;
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
if(i>=0){
printf("Name/s:\n");
for(i=0; i<nrNames;i++){
if(strcmp(input, name[i].name)==0){
printf("\n%s\n",name[i].name);
}
}
}
}
int readLine(char s[], int length){
int ch, i=0;
while(isspace(ch=getchar()));
while(ch!='\n' && ch!=EOF) {
if(i<length) s[i++]=ch;
ch = getchar();
}
s[i]='\0';
return i;
}
Try to search for the match in the array. The code below displays a position for each occurrence of the second array in the first array. It uses naive approach. There are more efficient algorithms like Knuth-Morris-Pratt or Boyer-Moore algorithm.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
int main(){
char c;
char name[MAX], search_name[MAX];
int i = 0, j = 0, match = 0, count = 0;
printf("Register name: ");
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
name[i++] = c;
}
}
name[i] = '\0';
printf("Search name: ");
i = 0;
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
search_name[i++] = c;
}
}
search_name[i] = '\0';
i=-1;
match = 0;
do {
i++;
j = 0;
do {
if (name[i+j] == search_name[j])
match = 1;
else {
match = 0;
break;
}
j++;
} while (search_name[j] != '\0');
if (match)
printf("Match on position %d ", i);
} while (name[i+j] != '\0');
printf("\n");
return 0;
}
I found the soulution myself. Here is the code for those who get stuck as I did.
void searchName(const struct varor reg[], int nrOfGoods){
int i;
char name[20];
printf("Enter name: ");
readLine(name, WORDLENGTH);//gets input
if(i>=0){
printf("\nId.number \t Name \t\t\t Quantity\n");
for(i=0; i<nrOfGoods;i++){
if(strstr(reg[i].name, name)!=NULL){ //this should do the job
printf("%-17d%-24s%-5d\n",reg[i].idnumber,reg[i].name.reg[i].quantity);
}
}
}
}
I need to convert an ascii input to hex input. I am very bad with C so if you could include some explanation that would be very helpful. This code is just a bunch of bits and pieces but most is probably wrong or useless. Afterwards i need to use user input to select the string but the hard part is getting it to convert at all.
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
void crypt(char *buf, char *keybuf, int keylen) {
//This is meant to encrypt by xor-ing with the sentence and key entered//
//It is also supposed to replace the original buf with the new version post-xor//
int i;
int *xp;
xp=&i;
for(i=0; i<keylen; i++) {
buf[i]=buf[i]^keybuf[i];
xp++;
}
}
int convertkey(char *keybuf) {
int keylen=0;
//I need to add something that will return the length of the key by incrementing keylen according to *keybuf//
return keylen;
}
int main(int argc, char * argv[]){
char x;
char *xp;
xp = &x;
char a[47];
char *ap;
ap=a;
printf("Enter Sentence: ");
scanf("%[^\n]",a);
printf("Enter key: ");
scanf("%d",xp);
printf("You entered the sentence: %s\n",a);
printf("You entered the key: %d\n",x);
convertkey(xp);
crypt(ap,xp,x);
printf("New Sentence: %s\n",a);
return 0;
}
Such as it is, I have reorganised your posted code so at least it compiles, even if the intent is unclear. Perhaps you can take it on from here.
#include <stdio.h>
#include <stdlib.h>
// moved out of main()
void crypt(char *buf, char *keybuf, int keylen) {
int i; // added declaration
for(i=0; i<keylen; i++) { // corrected syntax and end condition
buf[i]=buf[i]^keybuf[i];
//xp++; // out of scope
}
}
// moved out of main()
int convertkey(char *keybuf) {
int keylen=0;
return keylen;
}
int main(int argc, char * argv[]){
int x=0;
int *xp;
xp = &x; // xp=&x{0};
return 0; // exit(0);
}
This is the final product I was looking for but was very poor at explaining/coding.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void crypt(char *buf, char *keybuf, int keylen) {
int i;
int length= strlen(buf)-1;
for(i=0; i<length; i++) {
buf[i]=buf[i]^keybuf[i%keylen];
printf("%c",buf[i]);
}
printf("\n");
}
int convertkey(char *keybuf) {
int i=0;
for(i=0;keybuf[i]!='\n';i++){
if(keybuf[i]>='0' & keybuf[i]<='9'){
keybuf[i]=keybuf[i]-'0';
}
else if(keybuf[i]>='a' & keybuf[i]<='f'){
keybuf[i]=(keybuf[i]-'a')+10;
}
}
return i;
}
int main(int argc, char * argv[]){
char keychars[12];
char a[48];
char *ap;
int i;
ap=a;
printf("Enter Sentence: ");
fgets(a, 48, stdin);
printf("Enter Key: ");
fgets(keychars, 12, stdin);
for (i=0; i<strlen(keychars); i++) {
char c = keychars[i];
printf("keychars[%d]=%c (character), %d (decimal), %x (hex)\n", i, c, c, c);
}
crypt(ap,keychars,convertkey(keychars));
return 0;
}