Answer the question
In order to leave comments, you need to log in
How to check some characters before and after another character in C?
From the keyboard, enter a character string, in which, in addition to words, there can be integers
and real numbers, in which the fractional part is separated by a comma.
Extract all numbers from this string. Printing an abbreviated string. Hint:
to remove numbers, you need to shift all subsequent words to the left.
Here is my code:
#include <stdio.h>
int main(void) {
char in[100]; //массив символів для вхідної строки
char out[100]; //массив символів для вихідної строки
int indexIN = 0, //індекс массиву символів вхідної строки
indexOUT = 0; //індекс массиву символів результуючої строки
printf("Vvedit stroku:\n");
gets_s(in);
while (in[indexIN] != '\0')
{
if (in[indexIN] >= '0' && in[indexIN] <= '9')
indexIN++;
else
{
out[indexOUT] = in[indexIN];
indexIN++;
indexOUT++;
}
}
out[indexOUT] = '\0'; //додаємо символ кінца строки в результуючий массив
puts(out);
return 0;
}
Answer the question
In order to leave comments, you need to log in
Just look two characters ahead, if they are a comma and a number then remove them.
#include <stdio.h>
#include <stdbool.h>
static inline bool isDigit(char c) {
return c >= '0' && c <= '9';
}
int main() {
char in[100], out[100];
int indexIN = 0, indexOUT = 0;
puts("Введите строку");
fgets(in, 100, stdin);
while(indexIN < sizeof(in) && in[indexIN]) {
if (isDigit(in[indexIN])) {
// Если два следующих символа - запятая и цифра
if(indexIN < sizeof(in)-2 && in[indexIN+1] == ',' && isDigit(in[indexIN+2]))
indexIN += 2;
indexIN++;
} else {
out[indexOUT++] = in[indexIN++];
}
}
out[indexOUT] = 0;
puts(out);
}
I'm thinking of doing a character check before and after the comma, but don't know how. Help me please.Check for the number of characters
in[indexIN - 1]
and in[indexIN + 1]
, while taking into account the overflow when indexIN == 0
. #define IS_DIGIT(I) (in[(I)] >= '0' && in[(I)] <= '9')
if (IS_DIGIT(indexIN) || (in[indexIN] == ',' && indexIN != 0 && IS_DIGIT(indexIN - 1) && IS_DIGIT(indexIN + 1)))
indexIN++;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question