Open In App

Check length of a string is equal to the number appended at its last

Last Updated : 20 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string that (may) be appended with a number at last. You need to find whether the length of string excluding that number is equal to that number. For example for “helloworld10”, answer is True as helloworld consist of 10 letters. Length of String is less than 10, 000.

Examples : 

Input:  str = "geeks5"
Output: Yes
Explanation : As geeks is of 5 length and at
last number is also 5.
Input: str = "geeksforgeeks15"
Output: No
Explanation: As geeksforgeeks is of 13 length and
at last number is 15 i.e. not equal

Asked in: Codenation Interview

A Naive approach is to traverse from starting and retrieve the number from string and check if length of string – digits in the number = number or Not 

An efficient method is to do following steps  

  1. Traverse string from end and keep storing the number till it is smaller than the length of the overall string.
  2. If the number is equal to length of string except that number’s digits then return true. 
  3. Else return false.

Implementation:

C++
// C++ program to check if size of string is appended
// at the end or not.
#include <bits/stdc++.h>
using namespace std;

// Function to find if given number is equal to
// length or not
bool isequal(string str)
{
    int n = str.length();

    // Traverse string from end and find the number
    // stored at the end.
    // x is used to store power of 10.
    int num = 0, x = 1, i = n - 1;
    for (i = n - 1; i >= 0; i--) {
        if ('0' <= str[i] && str[i] <= '9') {
            num = (str[i] - '0') * x + num;
            x = x * 10;
            if(num>=n)
                return false;
        }
        else
            break;
    }

    // Check if number is equal to string length except
    // that number's digits
    return num == i + 1;
}

// Drivers code
int main()
{
    string str = "geeksforgeeks13";
    isequal(str) ? cout << "Yes" : cout << "No";
    return 0;
}
Java
// Java program to check if size of
// string is appended at the end or not.
import java.io.*;

class GFG {

    // Function to find if given number is 
    // equal to length or not
    static boolean isequal(String str)
    {
        int n = str.length();

        // Traverse string from end and find the number
        // stored at the end.
        // x is used to store power of 10.
        int num = 0, x = 1, i = n - 1;
        for (i = n - 1; i >= 0; i--) 
        {
            if ('0' <= str.charAt(i) && 
                str.charAt(i) <= '9')
            {
                num = (str.charAt(i) - '0') * x + num;
                x = x * 10;
                if(num>=n)
                    return false;
            }
            else
                break;
        }

        // Check if number is equal to string 
        // length except that number's digits
        return num == i + 1;
    }

    // Drivers code
    static public void main(String[] args)
    {
        String str = "geeksforgeeks13";
        if (isequal(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

// This Code is contributed by vt_m.
Python3
# Python 3 program to check if size of 
# string is appended at the end or not.

# Function to find if given number 
# is equal to length or not
def isequal(str):

    n = len(str)

    # Traverse string from end and 
    # find the number stored at the end.
    # x is used to store power of 10.
    num = 0
    x = 1
    i = n - 1
    for i in range(n - 1, -1,-1) :
        if ('0' <= str[i] and str[i] <= '9') :
            num = (ord(str[i]) - ord('0')) * x + num
            x = x * 10
            if (num>=n):
                return false
    
        else:
            break

    # Check if number is equal to string 
    # length except that number's digits
    return num == i + 1

# Driver Code
if __name__ == "__main__":
    
    str = "geeksforgeeks13"
    print("Yes") if isequal(str) else print("No")

# This code is contributed by ChitraNayal
C#
// C# program to check if size of 
// string is appended at the end or not.
using System;

class GFG {

    // Function to find if given number 
    // is equal to length or not
    static bool isequal(string str)
    {
        int n = str.Length;

        // Traverse string from end and find the number
        // stored at the end.
        // x is used to store power of 10.
        int num = 0, x = 1, i = n - 1;
        for (i = n - 1; i >= 0; i--) 
        {
            if ('0' <= str[i] && str[i] <= '9') {
                num = (str[i] - '0') * x + num;
                x = x * 10;
                if(num>=n)
                    return false;
            }
            else
                break;
        }

        // Check if number is equal to string 
        // length except that number's digits
        return num == i + 1;
    }

    // Drivers code
    static public void Main()
    {
        string str = "geeksforgeeks13";
        if (isequal(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}

// This Code is contributed by vt_m.
Javascript
<script>

// Javascript program to check if size of
// string is appended at the end or not.

// Function to find if given number is 
// equal to length or not
function isequal(str)
{
    let n = str.length;

    // Traverse string from end and find 
    // the number stored at the end.
    // x is used to store power of 10.
    let num = 0, x = 1, i = n - 1;
    for(i = n - 1; i >= 0; i--) 
    {
        if ('0' <= str[i] && 
            str[i] <= '9')
        {
            num = (str[i] - '0') * x + num;
            x = x * 10;
            
            if (num >= n)
                return false;
        }
        else
            break;
    }

    // Check if number is equal to string 
    // length except that number's digits
    return num == i + 1;
}

// Driver code
let str = "geeksforgeeks13";

if (isequal(str))
    document.write("Yes");
else
    document.write("No");

// This code is contributed by rag2127

</script> 
PHP
<?php
// PHP program to check if size 
// of string is appended at 
// the end or not.

// Function to find if given 
// number is equal to length or not
function isequal($str)
{
    $n = strlen($str);

    // Traverse string from end 
    // and find the number stored 
    // at the end. x is used to 
    // store power of 10.
    $num = 0; $x = 1; $i = $n - 1;
    for ($i = $n - 1; $i >= 0; $i--) 
    {
        if ('0' <= $str[$i] && 
                   $str[$i] <= '9') 
        {
            $num = ($str[$i] - '0') * 
                           $x + $num;
            $x = $x * 10;
            if($num>=$n)
                return false;
        }
        else
            break;
    }

    // Check if number is equal 
    // to string length except
    // that number's digits
    return $num == $i + 1;
}

// Driver code
$str = "geeksforgeeks13";
if(isequal($str)) 
echo "Yes" ;
else
echo "No";
return 0;

// This code is contributed by nitin mittal. 
?>

Output
Yes

Time complexity: O(n) where n is length of the string
Auxiliary space: O(1)

Approach#2: Using is.digit()

First, the length of the input string is calculated, and 1 is subtracted from it to exclude the last character, which is expected to be a number. Then, the isdigit() method is used to check if the last character of the string is a digit. If the last character is a digit, the code converts it into an integer and compares it with the length of the string. If they are equal, it means the length of the string is equal to the number appended at the end of the string.

Algorithm

1. Initialize a variable str with the input string.
2. Calculate the length of the string and store it in the variable length.
3. Subtract 1 from length to exclude the last character from the length calculation.
4. Check if the last character of the string is a digit using the isdigit() method.
5. If the last character is a digit, convert it into an integer using the int() function.
6. Compare the integer with length.
7. If they are equal, print “Yes”; otherwise, print “No”.

C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "geeksforgeeks15";
    int length = str.length() - 1; // subtract 1 to exclude the last character, which should be a number
    if (isdigit(str[length]) && stoi(str.substr(length)) == length) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
    return 0;
}
Java
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String str = "geeksforgeeks15";
        int length = str.length() - 1; // Subtract 1 to exclude the last character, which should be a number
        
        // Check if the last character is a digit and the substring 
       // from the last character till the end of the string
      // represents a valid number that is equal to the length of the string
        if (Character.isDigit(str.charAt(length)) && Integer.parseInt(str.substring(length)) == length) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
Python3
str = "geeksforgeeks15"
length = len(str) - 1  # subtract 1 to exclude the last character, which should be a number
if str[length:].isdigit() and int(str[length:]) == length:
    print("Yes")
else:
    print("No")
C#
using System;

namespace MainNamespace
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string str = "geeksforgeeks15";
            int length = str.Length - 1; // Subtract 1 to exclude the last character, which should be a number

            // Check if the last character is a digit and the substring 
            // from the last character till the end of the string
            // represents a valid number that is equal to the length of the string
            if (char.IsDigit(str[length]) && int.Parse(str.Substring(length)) == length)
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No");
            }
        }
    }
}

// This code is contributed by shivamgupta0987654321
Javascript
// Define the main function
function main() {
    // Define a string
    var str = "geeksforgeeks15";

    // Calculate the length of the string, excluding the last character
    var length = str.length - 1;

    // Check if the last character is a digit and if the numeric portion of the string is equal to the length
    if (isDigit(str[length]) && parseInt(str.substr(length)) === length) {
        console.log("Yes"); // Output "Yes" if the condition is true
    } else {
        console.log("No");  // Output "No" if the condition is false
    }
}

// Function to check if a character is a digit
function isDigit(char) {
    return /\d/.test(char);
}

// Call the main function to execute the code
main();

// This code is contributed by shivamgupta0987654321

Output
No

Time Complexity: O(1), The algorithm has constant time complexity because it performs a fixed number of operations, regardless of the length of the input string.
Space Complexity: O(1), The algorithm uses a fixed amount of memory to store the input string, length, and a few variables, so the space complexity is constant.

Regrex Approach :

Follow the given steps to solve the problem :

  • Use regular expressions to separate the string from the number at the end
  • Extract the string part and the number part
  • Convert the number part to an integer
  • Compare the length of the string part with the number
  • Return Yes if they are equal, No otherwise.

Below is the implementation of the above approach:

Python3
import re

def check_length(str):
    # Use regular expression to extract string and number parts
    match = re.match(r'([a-zA-Z]+)(\d+)$', str)
    
    # If no match is found, return "No"
    if not match:
        return "No"
    
    # Extract string and number parts
    string_part = match.group(1)
    number_part = int(match.group(2))
    
    # Check if length of string part matches the number part
    if len(string_part) == number_part:
        return "Yes"
    else:
        return "No"

print(check_length("geeks5")) 
JavaScript
function checkLength(str) {
    // Use regular expression to extract string and number parts
    const match = str.match(/^([a-zA-Z]+)(\d+)$/);

    // If no match is found, return "No"
    if (!match) {
        return "No";
    }

    // Extract string and number parts
    const stringPart = match[1];
    const numberPart = parseInt(match[2]);

    // Check if length of string part matches the number part
    if (stringPart.length === numberPart) {
        return "Yes";
    } else {
        return "No";
    }
}

console.log(checkLength("geeks5"));

Output
Yes

Time Complexity: O(n), where n is the length of the input string.

Auxiliary Space: O(1)




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads