Open In App

C Program To Remove Leading Zeros

Last Updated : 29 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Here, we will build a C Program to Remove leading zeros with the following 2 approaches:

  1. Using for loop
  2. Using strspn 

To remove all leading zeros from a number we have to give the input number as a string.

Input:

a = "0001234" 

Output: 

1234

1. Using for loop

C




// C Program to Remove leading zeros
// using for loop
#include <stdio.h>
#include <string.h>
int main()
{
    // input
    char a[1000] = "0001234";
    int i, c = -1;
    
    // finding the all leading zeroes from the given string
    // and removing it from the string
    for (i = 0; i < strlen(a); i++) {
        if (a[i] != '0') {
            c = i;
            break;
        }
    }
    // printing the string again after removing the all
    // zeros
    for (i = c; i < strlen(a); i++) {
        printf("%c", a[i]);
    }
    return 0;
}


Output

1234

2. Using strspn 

strspn: Returns the length of the first segment of str1 that exclusively contains characters from str2.

C




// C Program to Remove leading zeros
// using strspn
#include <stdio.h>
#include <string.h>
int main()
{
    // input string
    char* s = "0001234";
    int n;
    
    // strspn->Returns the length of the first segment of
    // str1 that exclusively contains characters from str2.
    if ((n = strspn(s, "0")) != 0 && s[n] != '\0') {
        
        // printing the string after eliminating the zeros
        printf("%s", &s[n]);
    }
    return 0;
}


Output

1234


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads