How to check certain chars in string in C? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Suppose ,I have to use only one string function and check if the string input by user contains all the chars a,e,i,o,u ...how do I do it?
(the chars mentioned above need not be contagious in the string input by user.)
Please help.

You can use the function strchr
char *strchr(const char *str, int c)
This function searches for the first occurrence of the character c (an unsigned char) in the string pointed to by the argument str.
If the character c is not present then null is returned.
One of the possible implementation is shown here -
#include <stdio.h>
#include <string.h>
#define SIZE 5
int main ()
{
char toCheck[5] = {'a','e','i','o','u'};
// Array of characters required in the string.
char userstring[25]; // User String
int i;
printf("Enter your string : \n");
scanf("%s",userstring);
for(i=0;i<SIZE;i++ ){
if(strchr(userstring,toCheck[i])==NULL)
break;
}
if(i==SIZE)
printf("All Required Characters present");
else printf("All Required Characters not present");
return 0;
}

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool containsAll(const char *input, const char *contains){
bool check[256] = { false };
while(*input){
check[(unsigned char)*input++] = true;
}
while(*contains){
if(!check[(unsigned char)*contains++])
return false;
}
return true;
}
int main(void){
char input[256];
fgets(input, sizeof input, stdin);
input[strcspn(input, "\n")] = 0;
if(containsAll(input, "aeiuo"))//"aeiuo\n"
puts("yes");
else
puts("no");
}

Related

Why do I have different output then expected when I input a word that has the same length (or bigger) as default char-array length? [duplicate]

This question already has an answer here:
What are null-terminated strings?
(1 answer)
Closed 9 months ago.
Why do I have different output then expected when I input a word that has the same length (or bigger) as default char-array length
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char word[4];
printf("Write a string: ");
scanf("%s", word);
int lenght = strlen( word );
int j = lenght-1;
for (size_t i = 0; i < lenght/2; i++)
{
char temp = word[i];
word[i]=word[j];
word[j] = temp;
j--;
}
printf("%s", word); //reversed string
return 0;
}
e.g input is "kill"
expected output is "llik"
actuall output is llikiā™¦
but when I fill that array using scanf() with word "kill" and then use printf("%s",word) I see that there is no problems with having words longer than 4 in word[]
Your program is OK
Here it seems that all is well

Storing a variable integer with a char Array in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to extract, edit and re-concatenate a string that contains an integer. How does this get done?
char str_test[] = "CAT ";
int count = 10;
//(1) something here to combine str_test and count stored in some variable
char str_new[] = ????;
//(2) something else here to extract the 10 and +1?
//such that if I print str_new, it gives me "CAT 11"
????
You can use sprintf to write a formatted number to a string, and you can use snprintf to find out how many characters are required.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Return a newly allocated string containing String followed by Number
converted to decimal. The caller is responsible for freeing the memory.
*/
static char *ConcatenateIntToString(const char *String, int Number)
{
// Get the number of non-null characters in String.
size_t Length = strlen(String);
/* Allocate space for:
the characters in String,
the characters needed to format Number with "%d", and
a terminating null byte.
*/
char *Result = malloc(
Length
+ snprintf(NULL, 0, "%d", Number)
+ 1);
// Test whether the allocation succeeded.
if (!Result)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
// Copy the characters from String.
memcpy(Result, String, Length);
// Append the formatted number and a null terminator.
sprintf(Result + Length, "%d", Number);
// Return the new string.
return Result;
}
int main(void)
{
char *NewString = ConcatenateIntToString("CAT ", 11);
printf("The new string is %s.\n", NewString);
free(NewString);
}

csv file visualization program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I would like to write a program that will open a csv file and create its visualization in a txt file.
I mean:
input:
(this is csv file)
apple;orange;strawberry
car;warsaw;ansi
output in txt file
apple|orange|strawberry
car |warsaw| ansi
The idea is that the width of the whole column should be adjusted to the longest expression in it
output in my program
apple|orange|strawberry
|car|warsaw|ansi
|
I have too many separators, and they're not in line
My code:
#include <stdio.h>
#include <string.h>
#include <string.h>
#define MAXLINE 1000
int how_many_delimiter(char array[]);
int main(void)
{
FILE *f,*f_2;
int *size_of_column, counter, hmd, min;
char corrector[] = ";", rows[MAXLINE], *clipboard;
f = fopen("ex-5.csv", "r");
f_2 = fopen("wynik.txt", "w");
fgets(rows, MAXLINE, f);
hmd = how_many_delimiter(rows);
size_of_column = (int*)calloc(hmd,sizeof(int));
min=10;
while(fgets(rows, MAXLINE, f))
{
clipboard = strtok(rows, corrector);
counter=0;
if(strlen(clipboard)>size_of_column[counter])
{
size_of_column[counter] = strlen(clipboard);
}
while(clipboard!=NULL)
{
if(strlen(clipboard)>size_of_column[counter])
{
size_of_column[counter] = strlen(clipboard);
}
clipboard = strtok(NULL,corrector);
counter++;
}
}
fclose(f);
f = fopen("ex-5.csv", "r");
while(fgets(rows, MAXLINE, f))
{
clipboard = strtok(rows, corrector);
counter=0;
while(clipboard!=NULL)
{
fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);
clipboard = strtok(NULL,corrector);
counter++;
}
}
fclose(f);
fclose(f_2);
return 0;
}
int how_many_delimiter(char array[])
{
int counter, i;
i = 0;
counter = 1;
while(array[i]!='\n'&& array[i]!=EOF)
{
if(array[i]==';') counter++;
i++;
}
return counter;
}
Steps to do this (using an alternate to the "%*s", width method):
Loop to get length of longest word in all categories
int len = strlen(longestWord);
Create format string container char formatStr[80];
Populate formatStr: sprintf(formatStr, "%s%d%s", "%", len+5, "s");
+5 is arbitrary, change as needed for space between columns.
Use formatStr in the printf() statements for each word.
So for example the longest word shown in your example is strawberry. My suggestion was to programmatically parse all of the words into buffers, and loop on them, performing strlen() on each to determine longest. Once you've found, in this case, strawberry, len will be 10, so the format specifier would be "%15s" (if you use my recommended +5). But the value 15 will be in an int variable by then (say for example int longest. Since inserting it directly into the normal format string: ( "%longests" ) will not compile, it will need to be packaged up into a format string, formatStr as shown in bullets above, and here:
sprintf(formatStr, "%s%d%s", "%", longest + 5, "s|");
( Will look like: "%s15s|" )
Once this is done, you can use the format string in the printf statements
This then:
fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);
Becomes:
fprintf(f_2,formatStr, clipboard);
(either method will work.)

Replicating the Strlen function in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have been working on my C assignment where I try to replicate strlen() function without actually using it. This is the code I have been trying to get working. However, somehow the main function does not reflect what's happenning in mystrlen() function. Can you please tell me why it does not work as the strlen() function?
#include <stdio.h>
int mystrlen(char *input_string) {
/* This function returns the length of the input string */
/* WRITE FUNCTION CODE HERE! */
char str1[50];
int abcd = 0;
scanf("%s", str1);
int m;
for(m=0; str1[m]; m++){
abcd ++;
}
return 0;
}
int main(int argc, char **argv) {
int length;
if (argc!=2) {
printf("Usage: strlen <input_string_with_no_space_inside_it>\n\n");
return 1;
}
length = mystrlen(argv[1]);
printf("The length is: %d characters.\n",length);
return 0;
}
This:
return 0;
should be:
return abcd;
That said, abcd is a terrible name for this variable, and the function makes little sense as a strlen() replacement. It doesn't touch its argument, and calls scanf() to read input from the user, which you really don't want a strlen() replacement to do.
Here's one way of writing it:
size_t mystrlen(const char *s)
{
size_t len = 0;
if(s != NULL)
{
while(*s != '\0')
{
++len;
++s;
}
}
return len;
}
Improvements include:
Proper size_t-typed return value (lengths are sizes, and cannot be negative) so size_t is proper and what the real strlen() uses.
Doesn't do any input-reading.
Uses the input argument.
Computes length and returns it.
It also handles being given NULL, as a bonus.
A matching main() that does what yours did could be:
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Usage: strlen <input_string_with_no_space_inside_it>\n\n");
return 1;
}
const size_t length = mystrlen(argv[1]);
printf("The length is: %zu characters.\n", length);
return 0;
}
This basically centers around the int-to-size_t change. Also note that in shells supporting quoting, you can run your program like this:
$ ./strlen "hello this is a string with spaces in it"
and it will pass that entire quoted string (sans quotes, of course) in argv[1].
First of all, you try to pass a string, and then you invoke scanf function in mystrlen. Delete this scanf.
Secondly, your function always returns zero instead of value of variable abcd.

How to check if user did not enter all whitespace characters in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
When prompting the user to enter there name, it is necessary that the user indeed entered a name and not just whitespace.
Output ex:
Name:
Your name is: /user entered only whitespace/
How would one validate that characters were actually implemented, and not just spaces? Im using fgets() to retreive my input however i am unable to post the code now for I am at work and doing this off my mobile device. If code is nessesary i will post what im working on late tonight (pacific standard time). Thank you!
One way to test is to check all characters if they are space.
#include <stdio.h>
#include <stdlib.h>
// TODO: you should use bool instead
int is_all_space(const char *s)
{
char *tmp;
tmp = (char *) s;
// you might check for '\n' instead in your case
// or even '\r'
while (*tmp != '\0') {
// TODO: this check will fail if the input has zero length
if (*tmp != ' ') {
return 0;
}
tmp++;
}
return 1;
}
// don't forget to put the argument in quotes if it contains spaces
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s somestring\n", argv[0]);
exit(EXIT_FAILURE);
}
if (is_all_space(argv[1])) {
puts("Input is all-space and nothing else");
} else {
puts("Input it not all-space");
}
exit(EXIT_SUCCESS);
}

Resources