In my program i want to input a string of integer e.g 2107900000. I want to get its length and then want to remove all the 0's and 1's.
Perhaps not optimal, but you could copy it into another buffer conditionally:
char buffer[20];
char num[] = "2107900000";
int j = 0;
for (int i = 0; num[i]; i++)
{
if (num[i] != '0' && num[i] != '1')
{
buffer[j] = num[i];
j++;
}
}
buffer[j] = 0 //null terminator
Or you could do it in a single buffer:
char num[] = "2107900000";
int j = 0;
for (int i = 0; num[i]; i++)
{
if (num[i] != '0' && num[i] != '1')
{
num[j] = num[i];
j++;
}
}
num[j] = 0 //null terminator
Supposing you want to construct a new string, and I'll assume that you want a function that simply accepts a pointer to such a string: (where it's assumed what's pointed at by stripped
is at least the same size as what's pointed at by orig
)
void strip_0s_and_1s(char *orig, char *stripped)
{
// while we haven't seen a null terminator
while(*orig){
// if the current character is not a 1 or a 0...
if(*orig != '0' && *orig != '1'){
// copy the character
*stripped= *orig;
stripped++;
}
// increment pointer to old string
orig++;
}
// terminate 'stripped' string
*stripped= '\0';
}
I believe calling this with the same pointer for both arguments should do the replacements in-place...
To address your question about finding length of input strings at runtime you can do something like:
#include <stdio.h>
#include <string.h>
int main (int argc, char **argv) {
int len;
char str[100]; // max string length of 99+1 null terminator
scanf("%s", str);
len = strlen(str);
printf("%d", len);
return 0;
}
(edit: changed to remove use of new
as a variable name)
(edit: added info about input strings at runtime and finding string length)
for (i=j=0; s[i]=s[j]; i+=((unsigned)s[j++]-'0'>2));
OK since there's demand for an explanation, the idea is to iterate through the string with 2 indices, a destination (i
) and source (j
). At each step, a character is copied from the source index to the destination index, and since the copy is the loop condition, it will terminate if the character copied is the null terminator. At each iteration, the source index gets incremented (j++
), but the destination index is only incremented if the character copied was not a 0 or a 1 (if it was one of these two characters, it will simply get overwritten on the next iteration). The test (unsigned)s[j++]-'0'>2
uses modular arithmetic and the property that the digits 0-9 have consecutive values as characters to perform an optimal test as to whether the source character is outside the range '0'
to '1'
, and this truth value (which evaluates to 0 or 1 for false or true, respectively) gets used as the amount to increment the destination index by.