Friday, December 27, 2024
Google search engine
HomeData Modelling & AIHow to find index of any Currency Symbols in a given string

How to find index of any Currency Symbols in a given string

Given a string txt, the task is to find the index of currency symbols present in the given string.
Examples: 
 

Input: txt = “Currency symbol of USA is $”; 
Output: 26 
Explanation : 
The symbol $ is present at index 33.
Input: txt = “One US Dollar($) is equal to 75.70 Indian Rupee.”; 
Output: 14 
 

 

Naive Approach: 
The simplest approach to solve the problem is to do the following: 
 

  • Create a set of all currencies.
  • Traverse the string and if any of the currency symbols present in the set is found in the string, print it’s index.

The above approach requires Auxiliary Space for storing all the currencies in the set.

Efficient Approach:

  1. The idea is to use Regular Expression to solve this problem.
  2. Create a regular expression to find currency symbol in the string as mentioned below : 
    regex = “\\p{Sc}“;
    Where: 
    {\\p{Sc} 
    represents any currency sign.
    For C++ / Python, we can use regex = “\\$|\\£|\\€
    Where the regex checks if any of the given currency symbol ( $, £, € ) is present in the string.
  3. Match the given string with the Regular Expression using Pattern.matcher().
  4. Print index of the character of the string for which a match is found with the given regular expression.

Below is the implementation of the above approach:

C++




// C++ program to find indices of
// currency symbols present in a
// string using regular expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to find currency symbol
// in a text using regular expression
void findCurrencySymbol(string text)
{
 
  // Regex to find any currency
  // symbol in a text
  const regex pattern("\\$|\\£|\\€");
  for (auto it = sregex_iterator(text.begin(), text.end(), pattern);
       it != sregex_iterator(); it++)
  {
     
      // flag type for determining the matching behavior
      // here it is for matches on 'string' objects
      smatch match;
      match = *it;
      cout << match.str(0) << " - " << match.position(0) << endl;
  }
  return ;
}
 
// Driver Code
int main()
{
  string txt
      = "$27 - $21.30equal to $5.70";
  findCurrencySymbol(txt);
  return 0;
}
 
// This code is contributed by yuvraj_chandra


Java




// Java program to find indices of
// currency symbols present in a
// string using regular expression
import java.util.regex.*;
class GFG {
 
    // Function to find currency symbol
    // in a text using regular expression
    public static void findCurrencySymbol(
        String text)
    {
 
        // Regex to find any currency
        // symbol in a text
        String regex = "\\p{Sc}";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(
            regex);
 
        // Find match between the
        // given string and the
        // Regex using Pattern.matcher()
        Matcher m = p.matcher(text);
 
        // Find the next subsequence
        // of the input subsequence
        // that matches the pattern
        while (m.find()) {
 
            System.out.println(
                text.charAt(m.start())
                + " - "
                + m.start());
        }
    }
    // Driver Code
    public static void main(String args[])
    {
        String txt = "$27 - $21.30"
                    + "equal to $5.70";
        findCurrencySymbol(txt);
    }
}


C#




// C# program to find indices of
// currency symbols present in a
// string using regular expression
using System;
using System.Text.RegularExpressions;
class GFG {
 
  // Function to find currency symbol
  // in a text using regular expression
  public static void findCurrencySymbol(
    string text)
  {
 
    // Regex to find any currency
    // symbol in a text
    string regex = "\\p{Sc}";
 
    // Compile the ReGex
    Regex p = new Regex(regex);
 
    // Find match between the
    // given string and the
    // Regex using Pattern.matcher()
    Match m = p.Match(text);
 
    // Find the next subsequence
    // of the input subsequence
    // that matches the pattern
    while (m.Success) {
 
      Console.WriteLine(
        text[m.Index]
        + " - "
        + m.Index);
 
      m = m.NextMatch();
    }
  }
  // Driver Code
  public static void Main()
  {
    string txt = "$27 - $21.30"
      + "equal to $5.70";
    findCurrencySymbol(txt);
  }
}
 
// This code is contributed by Aman Kumar.


Python3




# Python program to find indices of
# currency symbols present in a
# string using regular expression
import re
 
# Function to find currency symbol
# in a text using regular expression
def findCurrencySymbol(text):
 
    # Regex to find any currency
    # symbol in a text
    regex = "\\$|\\£|\\€"
 
    for m in re.finditer(regex, text):
        print(text[m.start(0)], "-" ,m.start(0))
 
 
# Driver code
txt = "$27 - $21.30equal to $5.70"
findCurrencySymbol(txt)
 
# This code is contributed by yuvraj_chandra


PHP




<?php
 
// Function to find currency symbols using regex
function findCurrencySymbol($text) {
    $regex = '/\p{Sc}/u'; // Regular expression to match any currency symbol
    $matches = [];
    preg_match_all($regex, $text, $matches, PREG_OFFSET_CAPTURE);
 
    // Print each matched currency symbol and its index position in the string
    foreach ($matches[0] as $match) {
        echo $match[0] . ' - ' . $match[1] . "\n";
    }
}
 
// Driver code
$txt = '$27 - $21.30equal to $5.70';
findCurrencySymbol($txt);


Javascript




function findCurrencySymbol(text) {
  const regex = /\p{Sc}/gu; // Regular expression to match any currency symbol
  let match;
  while ((match = regex.exec(text)) !== null) {
    console.log(`${match[0]} - ${match.index}`);
  }
}
 
// Driver Code
const txt = "$27 - $21.30equal to $5.70";
findCurrencySymbol(txt);


Output:

$ - 0
$ - 6
$ - 21

Time Complexity: O(N)

Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments