Finding characters in a sentence [closed] - c

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
I want to make a program that can find characters in long string...
.
.
int i = 0;
char buf[100];
char ch[10];
char *res;
int len = 0;
int j = 0;
printf("Enter characters: ");
while(1){
j = getchar();
if(j == '\n') break;
ch[i++] = j;
}
ch[i] = '\0';
while(len < 1){
printf("Enter a sentence: ");
res = fgets(buf, 200, stdin);
len = strlen(buf);
}
Here's sample execute screen.
Enter characters: mkn
Enter a sentence: My son is in elementary school.
Finding..
-
My
son
in
elementary
I want to make this program with strtok() and strchr()... but I am confused with pointers....

Though they may not be the best choices for this purpose, you can achieve what you want with strtok() and strchr(). Below is how I picture building on what you already have to get a working solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define CHARACTERS_MAXIMUM 32
#define BUFFER_MAXIMUM 1024
int main() {
char characters[CHARACTERS_MAXIMUM];
int characters_length = 0, character;
printf("Enter characters: ");
while (characters_length < CHARACTERS_MAXIMUM - 1) {
character = getchar();
if (character == '\n') {
break;
}
characters[characters_length++] = tolower(character);
characters[characters_length++] = toupper(character);
}
characters[characters_length] = '\0';
char buffer[BUFFER_MAXIMUM], *result = NULL;
int buffer_length = 0;
while (buffer_length < 1 || result == NULL) {
printf("Enter a sentence: ");
if ((result = fgets(buffer, BUFFER_MAXIMUM, stdin)) != NULL) {
buffer_length = strlen(buffer);
}
}
char *token = strtok(buffer, " ");
while (token != NULL) {
for (int i = 0; i < characters_length; i++) {
if (strchr(token, characters[i]) != NULL) {
printf("%s ", token);
break;
}
}
token = strtok(NULL, " ");
}
printf("\n");
return 0;
}
Note that this is not a finished program, there's more/better error checking you should do as well as other tweaks to finish it off properly.
USAGE EXAMPLE
> ./a.out
Enter characters: mkn
Enter a sentence: My son is in elementary school.
My son in elementary
>
Although the above is an appropriate use of strtok(), be wary of it. It is an artifact of an earlier age and should be avoided in favor of safer, modern library functions like strsep() or strtok_r().

Related

Segmentation fault. Converting a string to an integer

I have a problem where I'm trying to turn a value from an array of string pointers to an integer value: token[1]. However, I get a segmentation fault whenever I don't specify an integer at the first index which in some cases I won't need a number. For example what if I just wanted to type the command: list. I would get a segmentation fault after. How do I store the convert the string value at token[1] to an integer, if an integer is present or not?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(){
int ch, n = 1;
int i = 0;
int val = 0;
char str[512], *token[5], *act_token;
while(1){
printf("Enter text: ");
while((ch = getchar()) != '\n')
str[i++] = ch;
str[i] = '\0';
i = 0;
printf("string: %s\n", str);
int spaces = 0;
for(int counter = 0; counter < strlen(str) + 1; counter++){
if(str[counter] == ' '){
spaces++;
}
}
printf("Spaces: %d\n", spaces);
strtok(str, " ");
while(n <= spaces && (act_token = strtok(NULL, " "))){
token[n] = act_token;
n++;
}
token[n] = NULL;
n = 1;
// printf("token[1]: %s\n", token[1]);
for(int x = 1; x < spaces+1; x++){
printf("token[%d]: %s\n", x, token[x]);
}
if(isdigit(atoi(token[1])) != 0){
val = atoi(token[1]);
}
printf("value:%d\n", val);
}
return 0;
}
I don't know whether I understand you correctly. However, I have simply added some checks to prevent segfault that were occurring at varying points of the code. Tested with 'foo 3 33'. Formatting is poor.
int main(){
int ch, n = 1;
int i = 0;
int val = 0;
#define TOKEN_SZ 5
char str[512], *token[TOKEN_SZ+1], *act_token;
while(1){
printf("Enter text: ");
while((ch = getchar()) != '\n')
str[i++] = ch;
str[i] = '\0';
i = 0;
printf("string: %s\n", str);
int spaces = 0;
for(int counter = 0; counter < strlen(str) + 1; counter++){
if(str[counter] == ' '){
spaces++;
}
}
printf("Spaces: %d\n", spaces);
n=0;
strtok(str, " ");
while(n<TOKEN_SZ && n <= spaces && (act_token = strtok(NULL, " "))){
token[n] = act_token;
n++;
}
token[n] = NULL;
for(int i=0; token[i]; i++){
printf("%d token[%d]: %s\n", n,i, token[i]);
}
if(n>0 && (atoi(token[0])) != 0){
val = atoi(token[0]);
}
printf("value:%d\n", val);
}
return 0;
}
Update
bash> ./a.out
Enter text: list 2 4
string: list 2 4
Spaces: 2
2 token[0]: 2
2 token[1]: 4
value:2
Enter text:
Replace
if(isdigit(atoi(token[1])) != 0){
val = atoi(token[1]);
}
with
if(isdigit(token[1][0])) != 0){
val = atoi(token[1]);
}
The problem is that isdigit takes a character as its argument. Sure, the man page says it takes an integer, but that integer represents a character.
What your code is doing is:
convert token[1] to an integer (or 0 if it's not a valid integer)
determine whether that integer happens to match an ASCII digit
If so, convert it again, and save the value.
I doubt that's your intent.
My version checks whether the first character of token[1] is a digit, and converts the value if it is. Make sure you understand what token[1][0] means.
BTW, note that if you enter more than 5 space-separated words in your string, you'll store to tokens[6] and higher, which will produce undefined results (possibly crash.) Also, your program is wrong if the user enters more than two spaces between words.
Don't guess what strtok is going to do regarding how it detects and handles delimiters. Instead, let it do its job. Store the values as you get them. Either pick a limit value for the array where you're storing your results and exit the loop before exceeding it, or malloc space for more results as necessary. Here's an example:
char * tstr = str;
int tok_count = 0;
char *tok;
do {
tok = strtok(tstr, " ");
if (tok != NULL) {
token[tok_count++] = tok;
}
tstr = NULL;
} while (tok != NULL && tok_count < TOK_COUNT);
TOK_COUNT has to be at least 1, and should be the array size for tokens.

How to pick a word in a text line in C

How to pick a word in a text line in string in C language?
Example string "My mother cooks well...." How I can edit only "cooks" in that string? Question is for an exam. How can I find lenght and how can I edit second word in text, for example?
#include <stdio.h>
int length(char* s) // Lenght
{
int d = -1;
while (s[++d]);
return d;
}
int main() //main function
{
char str[101], c;
int i = 0;
printf("Entry text:\n");
scanf("%s", str); //Input text line
printf("First word lenght('%s') je %d.\n", str, lenght(str));
do
{
scanf("%c", &c);
str[i++] = c;
} while (c != '\n');
str[i - 1] = 0;
printf("The rest: '%s'\n", str); //Rest lenght
printf("The rest lenght: %d.", lenght(str));
return 0;
}
You can use strtok()
int i = 0;
char delim[2] = " ";
char *c = strtok(str, delim); //space is the delimiter.
// c points to the first word
while(c != NULL)
{
printf(" %s\n",c);
c = strtok(str, NULL) //notice this NULL
i++;
if(i == 2)
{
//edit your 2nd word
//break if you want after this or carry on
}
}
See strstr(3). I think that's all you need.

C Programme reading character by character into strings [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 7 years ago.
Improve this question
Basically what I'm doing is reading in a random text file, removing the punctuation and arranging the words into a linked list.
Everything works fine using this
printf("%c", (*(buf+x)));
so for example, the text file has the following
"they're their where ever we may go go,"
the correct out put is printed
theyre
their
where
ever
we
may
go
go
My problem is, how do I convert these into strings and store them in an array?
I'm assuming you want to reuse buf, so you want to copy the words into separately allocated storage. If you terminate each word in buf with a null byte prior to copying it, i.e. '\0', then you can use strdup to copy it. You can later free the space with free. Add the following includes (the second is for free):
#include <string.h>
#include <stdlib.h>
Here's a simple example:
buf[0] = 'a';
buf[1] = 'b';
buf[2] = 'c';
buf[3] = '\0';
str = strdup(buf);
I assume you want to store the words from the file in an array and print them.
you can try the following:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *buf[40];
for (int n = 0; n < 40; n++)
{
buf[n] = (char*)malloc(20 * sizeof(char));
}
FILE *file;
fopen_s(&file, "file.txt", "r");
int c, i = 0, j = 0;
bool init = 0;
while ((c = getc(file)) != EOF)
{
if (c != ' ')
{
buf[i][j] = c;
j++;
init = 1;
}
else
{
if (init)
{
buf[i][j] = '\0';
i++;
j = 0, init = 0;
}
}
}
buf[i][j] = '\0';
for (int x = 0; x <= i; x++)
{
printf("word[%d] : %s\n", x, buf[x]);
}
for (int x = 0; x < 40; x++)
{
free(buf[x]);
}
fclose(file);
return 0;
}
Try this code to understand better concept :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char c;
int i = 0, count = 0,max = 0;
FILE *fp;
fp = fopen("file.txt", "r");
if(fp == 0)
{
printf("File is not opened\n");
return;
}
else
{
// Finding line having maximum characters from the file to allocate that much memory..
while ((c = getc(fp)) != EOF)
{
count++;
if(c == '\n')
{
if(count > max)
max = count;
count = 0;
}
else
{
count = 0;
}
}
}
rewind(fp);
// Allocating the memory up to max line from the file.
char *temp = (char*)malloc(max * sizeof(char));
while ((c = getc(fp)) != EOF)
{
if ((c >= 'a' && c<='z') || (c >= 'A' && c <= 'z'))
{
temp[i++] = c;
}
else if(c == ' ' || c == '\n')
{
temp[i] = '\0';
printf("%s\n",temp);
i = 0;
memset(temp,'\0',max);
}
}
free(temp);
fclose(fp);
return 0;
}

Dynamic allocation of char** [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 7 years ago.
Improve this question
This is the text of my example:
Loading number N then N words from standard input. The word is not longer than 100 characters. Dynamically allocate array of loaded words as a series of pointers to character strings (dynamic array needs to have a type char **). Provide a set of words printed in a single line with spaces between the words.
Can someone tell me how to set the character limits?
Should I do this:
scanf("%100s", str[i])
or something else?
BTW, how can I allocate the memory for a type like this (char **,int **,etc)?
This is my code that I've done, so what have I done wrong?
int main()
{
int i,n;
printf("How much words? "), scanf("%d", &n);
char *str= (char *)malloc(n*sizeof(char *));
for(i = 0; i < n; i++)
{
str[i] = malloc(100 * sizeof(char *));
printf("%d. word: ", i + 1),scanf("%s", str[i]);
}
for (i = 0; i < n; i++)
{
printf("%s ", str[i]);
}
getch();
Wrong type for array of pointers
// char *str
char **str
Code clean-up with comments.
// add void
int main(void) {
int i,n;
// Easier to understand if on 2 lines-of code
printf("How much words? ");
// test scanf() results
if (scanf("%d", &n) != 1) return -1;
// Consider different style to allocate memory, as well as type change
// char *str= (char *)malloc(n*sizeof(char *));
char **str= malloc(sizeof *str * n);
// check allocation
assert(str == NULL);
for(i = 0; i < n; i++) {
str[i] = malloc(sizeof *str[i] * 100);
// check allocation
assert(str[i] == NULL);
printf("%d. word: ", i + 1);
fflush(stdout);
// limit input width to 99
// test scanf() results
if (scanf("%99s", str[i]) != 1) return -1;
}
for (i = 0; i < n; i++) {
// Add () to clearly show beginning/end of string
printf("(%s) ", str[i]);
}
getch();
}

Count all characters in string but spaces [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I count sum of characters in string excluding blank spaces?! I wrote a code but it counts blank spaces too. Any suggestions? here is what I have:
void main()
{
char str[100];
int len, space;
printf( "Enter string:\n ");
printf("\n");
gets(str);
len = strlen(str);
printf("\n");
printf("\n No.of characters in string is %d " , len );
getch();
}
For simple spaces try this
len = strlen(str);
int nchar = 0
for(int i = 0; i != len; i++) {
if(str[i] != ' ') {
nchar++;
}
}
printf("nchar = %d\n", nchar);
For all whitespace ( space, tab, newline ) try this:
#include <ctype.h> // this line must be in the top of the file
len = strlen(str);
int nchar = 0;
for(int i = 0; i != len; i++) {
if(!isspace(str[i])) {
nchar++;
}
}
printf("nchar = %d\n", nchar);
Other ways you might see in code are:
int nchar = 0;
for(char *p = str; *p; nchar += (*p++ != ' '));
and
int nchar = 0;
for(char *p = str; *p; nchar += isspace(*p++) == 0);
But those are less obvious.
You need to iterate over string and check all characters, counting only non-space chars. Something like:
int i;
int len = strlen(str);
int count = 0;
for (i = 0; i < len; i++) {
char c = str[i];
if ( /* check that char is not space */ )
count++;
}
Alternatively, you can count all space characters and then calculate len - nspaces.

Resources