Program to insert dashes between two adjacent odd digits in given Number

07 Oct, 2021
Given a large number in form of string N, the task is to insert a dash between two adjacent odd digits in the given number in form of strings.
Examples:
Input: N = 1745389 Output: 1-745-389 Explanation: In string str, str[0] and str[1] both are the odd numbers in consecutive, so insert a dash between them.Input: N = 34657323128437 Output: 3465-7-323-12843-7
Bitwise Approach:
Traverse the whole string of numbers character by character.Compare every consecutive character using logical Bitwise OR and AND operators.If two consecutive characters of the string are odd, insert a dash (-) in them and check for the next two consecutive characters.
Traverse the whole string of numbers character by character.
Compare every consecutive character using logical Bitwise OR and AND operators.
If two consecutive characters of the string are odd, insert a dash (-) in them and check for the next two consecutive characters.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program for the above approach#include <iostream>#include <string>using namespace std; // Function to check if char ch is// odd or notbool checkOdd(char ch){    return ((ch - '0') & 1);} // Function to insert dash - between// any 2 consecutive digit in string strstring Insert_dash(string num_str){     string result_str = num_str;     // Traverse the string character    // by character    for (int x = 0;         x < num_str.length() - 1; x++) {         // Compare every consecutive        // character with the odd value        if (checkOdd(num_str[x])            && checkOdd(num_str[x + 1])) {             result_str.insert(x + 1, "-");            num_str = result_str;            x++;        }    }     // Print the resultant string    return result_str;} // Driver Codeint main(){     // Given number in form of string    string str = "1745389";     // Function Call    cout << Insert_dash(str);     return 0;}
// Java program to implement// the above approachclass GFG{ // Function to check if char ch is// odd or notstatic boolean checkOdd(char ch){    return ((ch - '0') & 1) != 0 ?            true : false;} // Function to insert dash - between// any 2 consecutive digit in string strstatic String Insert_dash(String num_str){    StringBuilder result_str = new StringBuilder(num_str);     // Traverse the string character    // by character    for(int x = 0; x < num_str.length() - 1; x++)    {         // Compare every consecutive        // character with the odd value        if (checkOdd(num_str.charAt(x)) &&            checkOdd(num_str.charAt(x + 1)))        {            result_str.insert(x + 1, "-");            num_str = result_str.toString();            x++;        }    }     // Print the resultant string    return result_str.toString();} // Driver Codepublic static void main(String[] args){         // Given number in form of string    String str = "1745389";     // Function call    System.out.println(Insert_dash(str));}} // This code is contributed by rutvik_56
# Python3 program for the above approach # Function to check if char ch is# odd or notdef checkOdd(ch):     return ((ord(ch) - 48) & 1) # Function to insert dash - between# any 2 consecutive digit in string strdef Insert_dash(num_str):     result_str = num_str     # Traverse the string character    # by character    x = 0    while(x < len(num_str) - 1):         # Compare every consecutive        # character with the odd value        if (checkOdd(num_str[x]) and            checkOdd(num_str[x + 1])):             result_str = (result_str[:x + 1] + '-' +                          result_str[x + 1:])            num_str = result_str            x += 1        x += 1     # Print the resultant string    return result_str # Driver Code # Given number in form of stringstr = "1745389" # Function callprint(Insert_dash(str)) # This code is contributed by vishu2908
// C# program to implement// the above approachusing System;using System.Text;class GFG{ // Function to check if char ch is// odd or notstatic bool checkOdd(char ch){    return ((ch - '0') & 1) != 0 ?            true : false;} // Function to insert dash - between// any 2 consecutive digit in string strstatic String Insert_dash(String num_str){    StringBuilder result_str = new StringBuilder(num_str);     // Traverse the string character    // by character    for(int x = 0; x < num_str.Length - 1; x++)    {         // Compare every consecutive        // character with the odd value        if (checkOdd(num_str[x]) &&            checkOdd(num_str[x + 1]))        {            result_str.Insert(x + 1, "-");            num_str = result_str.ToString();            x++;        }    }     // Print the resultant string    return result_str.ToString();} // Driver Codepublic static void Main(String[] args){         // Given number in form of string    String str = "1745389";     // Function call    Console.WriteLine(Insert_dash(str));}} // This code is contributed by Rajput-Ji
1-745-389
 
Time Complexity: O(N) Auxiliary Space: O(1) 
Regular Expression Approach:
The given problem can be solved using Regular Expression. The RE for this problem will be:  
(?<=[13579])(?=[13579])The given RE matches between odd numbers. We can replace the matched part of zero width with a dash, i.e.str = str.replaceAll(“(?<=[13579])(?=[13579])”, “-“);
Below is the implementation of the above approach:
C++
Java
Python
// C++ Program to implement// the above approach#include <iostream>#include <regex>using namespace std;  // Function to insert dash - between// any 2 consecutive odd digitstring Insert_dash(string str){     // Get the regex to be checked  const regex pattern("([13579])([13579])");   // Replaces the matched value  // (here dash) with given string  return regex_replace(str, pattern, "$1-$2");;} // Driver Codeint main(){  string str = "1745389";  cout << Insert_dash(str);  return 0;} // This code is contributed by yuvraj_chandra
// Java program for the above approach import java.util.regex.*; public class GFG {     // Function to insert dash - between    // any 2 consecutive odd digit    public static String Insert_dash(String str)    {         // Get the regex to be checked        String regex = "(?<=[13579])(?=[13579])";         // Create a pattern from regex        Pattern pattern = Pattern.compile(regex);         // Create a matcher for the input String        Matcher matcher            = pattern.matcher(str);         // Get the String to be replaced,        // i.e. here dash        String stringToBeReplaced = "-";        StringBuilder builder            = new StringBuilder();         // Replace every matched pattern        // with the target String        // using replaceAll() method        return (matcher                    .replaceAll(stringToBeReplaced));    }     // Driver Code    public static void main(String[] args)    {         // Given number in form of string        String str = "1745389";         // Function Call        System.out.println(Insert_dash(str));    }}
# Python program for the above approachimport re # Function to insert dash - between# any 2 consecutive odd digitdef Insert_dash(str):     # Get the regex to be checked    regex = "(?<=[13579])(?=[13579])"     return re.sub(regex,'\1-\2', str) # Driver Code # Given number in form of stringstr = "1745389" # Function Callprint(Insert_dash(str)) # This code is contributed by yuvraj_chandra
1-745-389
 
vishu2908
rutvik_56
Rajput-Ji
yuvraj_chandra
abhishek0719kadiyan
CPP-regex
java-regular-expression
number-digits
regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse the substrings of the given String according to the given Array of indices
Check if the given string is shuffled substring of another string
How to check Aadhaar number is valid or not using Regular Expression
How to validate GUID (Globally Unique Identifier) using Regular Expression
How to validate pin code of India using Regular Expression
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++