Home Blog Page 30

Regex for phone number validation – Regular Expression

0
regex for phone number.

Hi Guy’s Welcome to Proto Coders Point. In this article let’s checkout a regular expression for phone number validation.

I want a regex that matches following phone number pattern string:-

  • XXXXXXXXXX -> 10 digit mobile number validation.
  • +91 XXXXXXXXXX -> Country code + 10 digit phone number.
  • (XXX) XXX XXXX -> Phone number with brackets separator.
  • (XXX) XXX-XXXX -> Number with brackets & dash separator.
  • XXX-XXX-XXXX -> Phone Number with dash separator.

and much more.

Common Phone number group

  • Group1: Country Code (e.g. 1 or 86).
  • Group2: Area Code (e.g. 808).
  • Group3: Exchange (e.g. 555).
  • Group4: Subscriber Number (e.g.1234).
  • Group5: Extension (e.g. 5678).

Regular Expression for phone number validation

International phone number regex

^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$

Explanation of above phone number regex

^\s*Starting line , accept white space at beginning.
(?:\+?(\d{1,3}))?Match country code, here ‘?’ makes it optional. remove ‘?’ to validate phone number and make it mandatory.
[-. (]*Match special character like bracket which may appear between the country code & area code.
(\d{3})Area code of 3 digit in phone number string. add ‘?’ at end to make area code optional.
[-. )]*Match special character like bracket which may appear between the country code & area code.
(\d{3})Exchange Number of 3 digit in phone regex string. add ‘?’ at end to make area code optional.
[-. ]*Match special character like dash which may appear between.
(\d{4})Subscriber number of 4 digit in phone number string.
(?: *x(\d+))?Optional Extensional Number.
\s*$Accept any white space at ending of phone number string.

Remove brackets () from Phone Number string – Java | JavaScript

0
How to Remove Bracket () From Phone Number String

Hi Guy’s Welcome to Proto Coders Point. In this Article let’s check out How to remove brackets () from Phone Number String, With Java & JavaScript Code Example.

Java & JavaScript Code to check if phone number string contains () brackets and remove the brackets

Example:

+91 (123) 867 456              --->          +91 123 867 456

Java Code

public static void main(String[] args) {
      String phoneNo = "+91 (123) 867 456";
      Boolean bool = false;

      if(phoneNo.contains("(") || phoneNo.contains(")")){
          bool = true;
       }


      if(bool){
        String newphoneno = phoneNo.substring(0,4) + phoneNo.substring(5,8) + phoneNo.substring(9,phoneNo.length());
        
        System.out.println(""+newphoneno);
        //use replaceAll if you want to remove all empty spaces from string.
        System.out.println(""+newphoneno.replaceAll("\\s", ""));
        
   }
 }

use replaceAll(“\s”, “”) if you want to remove all empty spaces from string.


JavaScript Code

let phoneNo = "+91 (123) 867 456";
let bool = false;

if(phoneNo.includes("(") || phoneNo.includes(")")){
    bool = true;
}


if(bool){
    var newphoneno = phoneNo.substring(0,4) + phoneNo.substring(5,8)+phoneNo.substring(9,phoneNo.length);
}
console.log(newphoneno)
//use replace with regex if you want to remove all empty spaces from string.
console.log(newphoneno.replace(/\s+/g,''))

Here to remove spaces between the phone number string I am using replace with regular expression.

Implementation of stack using linked list with code example

0
Implementation of stack using linked list
stack linked list

Basic idea behind on How to write a program for linked list implementation of stack.

Stack Program using Linked List concept

Steps

The Code push() function must be similar to the code of inserting the node at the beginning of singly linked list.

The Code pop() function must be similar to the code of deleting the first node of singly linked list.

check if memory available, stack overflow occurs, when there is no spack left to insert data. In that case malloc() function will return NULL.

Check if stack is empty while removing the item, stack underflow will occurs when stack is empty.


C Program to implement stack using linked List

// C++ program to Implement a stack
// using singly linked list
#include <bits/stdc++.h>
using namespace std;

// creating a linked list;
class Node {
public:
	int data;
	Node* link;

	// Constructor
	Node(int n)
	{
		this->data = n;
		this->link = NULL;
	}
};

class Stack {
	Node* top;

public:
	Stack() { top = NULL; }

	void push(int data)
	{

		// Create new node temp and allocate memory in heap
		Node* temp = new Node(data);

		// Check if stack (heap) is full.
		// Then inserting an element would
		// lead to stack overflow
		if (!temp) {
			cout << "\nStack Overflow";
			exit(1);
		}

		// Initialize data into temp data field
		temp->data = data;

		// Put top pointer reference into temp link
		temp->link = top;

		// Make temp as top of Stack
		top = temp;
	}

	// Utility function to check if
	// the stack is empty or not
	bool isEmpty()
	{
		// If top is NULL it means that
		// there are no elements are in stack
		return top == NULL;
	}

	// Utility function to return top element in a stack
	int peek()
	{
		// If stack is not empty , return the top element
		if (!isEmpty())
			return top->data;
		else
			exit(1);
	}

	// Function to remove
	// a key from given queue q
	void pop()
	{
		Node* temp;

		// Check for stack underflow
		if (top == NULL) {
			cout << "\nStack Underflow" << endl;
			exit(1);
		}
		else {

			// Assign top to temp
			temp = top;

			// Assign second node to top
			top = top->link;

			// This will automatically destroy
			// the link between first node and second node

			// Release memory of top node
			// i.e delete the node
			free(temp);
		}
	}

	// Function to print all the
	// elements of the stack
	void display()
	{
		Node* temp;

		// Check for stack underflow
		if (top == NULL) {
			cout << "\nStack Underflow";
			exit(1);
		}
		else {
			temp = top;
			while (temp != NULL) {

				// Print node data
				cout << temp->data;

				// Assign temp link to temp
				temp = temp->link;
				if (temp != NULL)
					cout << " -> ";
			}
		}
	}
};

// Driven Program
int main()
{
	// Creating a stack
	Stack s;

	// Push the elements of stack
	s.push(11);
	s.push(22);
	s.push(33);
	s.push(44);

	// Display stack elements
	s.display();

	// Print top element of stack
	cout << "\nTop element is " << s.peek() << endl;

	// Delete top elements of stack
	s.pop();
	s.pop();

	// Display stack elements
	s.display();

	// Print top element of stack
	cout << "\nTop element is " << s.peek() << endl;

	return 0;
}

Java Program to implement stack using linked list concept

// Java program to Implement a stack
// using singly linked list
// import package
import static java.lang.System.exit;

// Driver code
class GFG {
	public static void main(String[] args)
	{
		// create Object of Implementing class
		StackUsingLinkedlist obj
			= new StackUsingLinkedlist();
		// insert Stack value
		obj.push(11);
		obj.push(22);
		obj.push(33);
		obj.push(44);

		// print Stack elements
		obj.display();

		// print Top element of Stack
		System.out.printf("\nTop element is %d\n",
						obj.peek());

		// Delete top element of Stack
		obj.pop();
		obj.pop();

		// print Stack elements
		obj.display();

		// print Top element of Stack
		System.out.printf("\nTop element is %d\n",
						obj.peek());
	}
}

// Create Stack Using Linked list
class StackUsingLinkedlist {

	// A linked list node
	private class Node {

		int data; // integer data
		Node link; // reference variable Node type
	}
	// create global top reference variable global
	Node top;
	// Constructor
	StackUsingLinkedlist() { this.top = null; }

	// Utility function to add an element x in the stack
	public void push(int x) // insert at the beginning
	{
		// create new node temp and allocate memory
		Node temp = new Node();

		// check if stack (heap) is full. Then inserting an
		// element would lead to stack overflow
		if (temp == null) {
			System.out.print("\nHeap Overflow");
			return;
		}

		// initialize data into temp data field
		temp.data = x;

		// put top reference into temp link
		temp.link = top;

		// update top reference
		top = temp;
	}

	// Utility function to check if the stack is empty or
	// not
	public boolean isEmpty() { return top == null; }

	// Utility function to return top element in a stack
	public int peek()
	{
		// check for empty stack
		if (!isEmpty()) {
			return top.data;
		}
		else {
			System.out.println("Stack is empty");
			return -1;
		}
	}

	// Utility function to pop top element from the stack
	public void pop() // remove at the beginning
	{
		// check for stack underflow
		if (top == null) {
			System.out.print("\nStack Underflow");
			return;
		}

		// update the top pointer to point to the next node
		top = (top).link;
	}

	public void display()
	{
		// check for stack underflow
		if (top == null) {
			System.out.printf("\nStack Underflow");
			exit(1);
		}
		else {
			Node temp = top;
			while (temp != null) {

				// print node data
				System.out.print(temp.data);

				// assign temp link to temp
				temp = temp.link;
				if(temp != null)
					System.out.print(" -> ");
			}
		}
	}
}

Python Program on stack linked list

# python3 program to Implement a stack
# using singly linked list

class Node:

	# Class to create nodes of linked list
	# constructor initializes node automatically
	def __init__(self, data):
		self.data = data
		self.next = None


class Stack:

	# head is default NULL
	def __init__(self):
		self.head = None

	# Checks if stack is empty
	def isempty(self):
		if self.head == None:
			return True
		else:
			return False

	# Method to add data to the stack
	# adds to the start of the stack
	def push(self, data):

		if self.head == None:
			self.head = Node(data)

		else:
			newnode = Node(data)
			newnode.next = self.head
			self.head = newnode

	# Remove element that is the current head (start of the stack)
	def pop(self):

		if self.isempty():
			return None

		else:
			# Removes the head node and makes
			# the preceding one the new head
			poppednode = self.head
			self.head = self.head.next
			poppednode.next = None
			return poppednode.data

	# Returns the head node data
	def peek(self):

		if self.isempty():
			return None

		else:
			return self.head.data

	# Prints out the stack
	def display(self):

		iternode = self.head
		if self.isempty():
			print("Stack Underflow")

		else:

			while(iternode != None):

				print(iternode.data, end = "")
				iternode = iternode.next
				if(iternode != None):
					print(" -> ", end = "")
			return


# Driver code
if __name__ == "__main__":
MyStack = Stack()

MyStack.push(11)
MyStack.push(22)
MyStack.push(33)
MyStack.push(44)

# Display stack elements
MyStack.display()

# Print top element of stack
print("\nTop element is ", MyStack.peek())

# Delete top elements of stack
MyStack.pop()
MyStack.pop()

# Display stack elements
MyStack.display()

# Print top element of stack
print("\nTop element is ", MyStack.peek())

Javascript stack implementation linked list

// Javascript program to Implement a stack
// using singly linked list
// import package

// A linked list node
class Node
{
	constructor()
	{
		this.data=0;
		this.link=null;
	}
}

// Create Stack Using Linked list
class StackUsingLinkedlist
{
	constructor()
	{
		this.top=null;
	}
	
	// Utility function to add an element x in the stack
	push(x)
	{
		// create new node temp and allocate memory
		let temp = new Node();

		// check if stack (heap) is full. Then inserting an
		// element would lead to stack overflow
		if (temp == null) {
			document.write("<br>Heap Overflow");
			return;
		}

		// initialize data into temp data field
		temp.data = x;

		// put top reference into temp link
		temp.link = this.top;

		// update top reference
		this.top = temp;
	}
	
	// Utility function to check if the stack is empty or not
	isEmpty()
	{
		return this.top == null;
	}
	
	// Utility function to return top element in a stack
	peek()
	{
		// check for empty stack
		if (!this.isEmpty()) {
			return this.top.data;
		}
		else {
			document.write("Stack is empty<br>");
			return -1;
		}
	}
	
	// Utility function to pop top element from the stack
	pop() // remove at the beginning
	{
		// check for stack underflow
		if (this.top == null) {
			document.write("<br>Stack Underflow");
			return;
		}

		// update the top pointer to point to the next node
		this.top = this.top.link;
	}
	
	display()
	{
		// check for stack underflow
		if (this.top == null) {
			document.write("<br>Stack Underflow");
			
		}
		else {
			let temp = this.top;
			while (temp != null) {

				// print node data
				document.write(temp.data+"->");

				// assign temp link to temp
				temp = temp.link;
			}
		}
	}
}

// main class

// create Object of Implementing class
let obj = new StackUsingLinkedlist();
// insert Stack value
obj.push(11);
obj.push(22);
obj.push(33);
obj.push(44);

// print Stack elements
obj.display();

// print Top element of Stack
document.write("<br>Top element is ", obj.peek()+"<br>");

// Delete top element of Stack
obj.pop();
obj.pop();

// print Stack elements
obj.display();

// print Top element of Stack
document.write("<br>Top element is ", obj.peek()+"<br>");

Data Structures and Algorithms Interview Questions – Quick Notes

0
Data Structures Interview Questions - quick notes revision

Hi Guy’s Welcome to Proto Coders Point. In this article let’s revise data structures and algorithms for interviews, basically will revise data structure interview questions that will be surely asked in any coding interview.

Data Structure quick revision to crack interview

1. What is Data Structure?

Data Structure simple means organizing, retrieving or storing of data in a specialized format, Basically data’s can be arranged in many ways like mathematical or logical arrangement, so technic of storing and retrieving of data is called as Data Structure.

2. What is Algorithms?

A technic in solving a given problem in a sequential steps performed on data is called algorithm.

3. Types of Data Structures

Data Structure are classified into two types:

  • Primitive.
  • Non-Primitive.

Example of Primitive data structure:  includes byte , short , int , long , float , double , boolean and char.

Example of Non- Primitive data structure such as Array, Linked list, stack, Classes.

4. Classification of Data Structure

 Classification of Data Structure

4. DS Array

Array is a type of linear data list, Using array we can store more then one data in a datatype using array. The data in array is been stored in a contiguous memory location.

Eg:

array in data structure

Types of array

One Dimensional Array: A Array with one subscript is called a 1D array.

Eg: int a[5];

Two Dimensional Array: A Array with two subscript is called a 2D array.

Eg: int a[3][3];

Multi Dimensional Array: A array with more then two subscript is called Multi Dimensional.

Eg: int a[5][4][2];


6. Data structures operations

There are for operations in data structure that plays major role:

Traversal :Accessing each record exactly once so that certain items in the record get processed.

Insertion : Adding data in the record.

Deletion: removing the data from the record.

Searching: Finding the location/position of particular item in the record with a given key value.

Sorting: Rearranging the data in accending or decending order.

Merging: combining the two or more data record as a single record.

6. Different of algorithm every developer should know

Searching algorithm

In DS, A search algorithms is a step-by-step procedure used to find the location if a data.

Types of Search algorithm in DS:-

1. Linear Search:

The linear search is also called as sequential search this is a method in data structure to search/find a element into the list in sequential order. Here each element is the list is check one by one until the match is been found.

complexity of linear search

C(n) = n/2.


2. Binary Search:

Here In Binary Search the element is been searched in the middle of the array list. This search technic is been implemented only for small list items.

Here first we need to check of the element are sorted or no, If not then first need to sort them in ascending order.

  • First begin the search at middle of array.
  • if the value search key is less then the item in the middle, then split it, and in next search only in first half.
  • or
  • if the value search key is greater then middle item, the split it, and search in second half.
  • repeat it until you find the element.

complexity of binary search

C(n) = log2n


And many other searching method like:

Interpolation Search

Jump Search

Exponential Search


Show Alert Dialog in flutter by using QuickAlert Package

0
Flutter Quick Alert Dialog
alert dialog in flutter

Hi Guy’s Welcome to Proto Coders Point. In this flutter tutorial let’s learn how to show alert dialog in flutter the quickest way by using QuickAlert dialog package.

Flutter quickalert

In flutter, If you are willing to show a Alert dialog then quickalert package is the best library to use. It’s an animated alert dialog using which we can show dialop popup alert like success alert, error alert, warning alert, confirm alert dialog box with just few lines of code.

Getting Started with Installation of flutter package

1. Add Dependencies

In your flutter project, Open pubspec.yaml file & under dependencies section add quickalert flutter package.

dependencies:
  flutter:
    sdk: flutter
  quickalert:   // add this line

Now hit pub get button or run flutter pub get command to download the flutter package as external library.

2. To use it Import quickalert.dart

import 'package:quickalert/quickalert.dart';

3. Syntax to Show Alert Dialog using quickalert

To display alert all you need to do is call QuickAlert.show() widget & define a alert type property to it.

Syntax

QuickAlert.show(
          context: context,
          type: QuickAlertType.success,
          text: 'Transaction Completed Successfully!',
          autoCloseDuration: const Duration(seconds: 2),
  );

When a button is clicked or any event or action occurs from user end, you need to just call above code.

Type of Flutter Alert Dialog

Success Alert

QuickAlert.show(
   context: context,
   type: QuickAlertType.success,
   text: 'Form Submitted Successfully!',
);

Confirm Alert

QuickAlert.show(
   context: context,
   type: QuickAlertType.confirm,
   text: 'Sure you want to logout?',
   confirmBtnText: 'Yes',
   cancelBtnText: 'No',
   confirmBtnColor: Colors.green,
  );

Error Alert

QuickAlert.show(
   context: context,
   type: QuickAlertType.error,
   title: 'Oops...',
   text: 'Error While Uploading the File, Please Retry ',
);

Warning Alert

QuickAlert.show(
   context: context,
   type: QuickAlertType.warning,
   title: 'Warning!',
   text: 'You are misusing the protocal',
  );

Info Alert

 QuickAlert.show(
   context: context,
   type: QuickAlertType.info,
   title: 'New Offer',
   text: 'Get Discount of 50% , On showing of Rs 5000',
  );

Loading Alert

QuickAlert.show(
   context: context,
   type: QuickAlertType.loading,
   title: 'Loading...',
   text: 'Please wait',
  );

Complete Source Code – QuickAlert Example

import 'package:flutter/material.dart';
import 'package:quickalert/quickalert.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    // success Alert
    final successAlert = buildButton(
      onTap: () {
        QuickAlert.show(
          context: context,
          type: QuickAlertType.success,
          text: 'Form Submitted Successfully!',
        );
      },
      title: 'Success',
      text: 'Transaction Completed Successfully!',
      leadingIcon: Icon(
        Icons.check_circle,
        color: Colors.green,
      ),
    );

    // error Alert
    final errorAlert = buildButton(
      onTap: () {
        QuickAlert.show(
          context: context,
          type: QuickAlertType.error,
          title: 'Oops...',
          text: 'Error While Uploading the File, Please Retry ',
        );
      },
      title: 'Error',
      text: 'Sorry, something went wrong',
      leadingIcon: Icon(
        Icons.error,
        color: Colors.red,
      ),
    );
    // warning Alert
    final warningAlert = buildButton(
      onTap: () {
        QuickAlert.show(
          context: context,
          type: QuickAlertType.warning,
          title: 'Warning!',
          text: 'You are misusing the protocal',
        );
      },
      title: 'Warning',
      text: 'You just broke protocol',
      leadingIcon: Icon(
        Icons.warning,
        color: Colors.red,
      ),
    );

    // info Alert
    final infoAlert = buildButton(
      onTap: () {
        QuickAlert.show(
          context: context,
          type: QuickAlertType.info,
          title: 'New Offer',
          text: 'Get Discount of 50% , On showing of Rs 5000',
        );
      },
      title: 'Info',
      text: 'Learn More..!',
      leadingIcon: Icon(
        Icons.info,
        color: Colors.grey,
      ),
    );

    // confirm Alert
    final confirmAlert = buildButton(
      onTap: () {
        QuickAlert.show(
          context: context,
          type: QuickAlertType.confirm,
          text: 'Sure you want to logout?',
          confirmBtnText: 'Yes',
          cancelBtnText: 'No',
          confirmBtnColor: Colors.green,
        );
      },
      title: 'Confirm',
      text: 'Do you want to logout',
      leadingIcon: Icon(
        Icons.logout,
        color: Colors.orange,
      ),
    );

    // loading
    final loadingAlert = buildButton(
      onTap: () {
        QuickAlert.show(
          context: context,
          type: QuickAlertType.loading,
          title: 'Loading...',
          text: 'Please wait',
        );
      },
      title: 'Loading',
      text: 'Please Wait',
      leadingIcon: Icon(
        Icons.downloading,
        color: Colors.greenAccent,
      ),
    );

    return Scaffold(
      backgroundColor: Colors.black54,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            successAlert,
            SizedBox(
              height: 20,
            ),
            errorAlert,
            SizedBox(
              height: 20,
            ),
            warningAlert,
            SizedBox(
              height: 20,
            ),
            infoAlert,
            SizedBox(
              height: 20,
            ),
            confirmAlert,
            SizedBox(
              height: 20,
            ),
            loadingAlert,
            ElevatedButton(
                onPressed: () {
                  QuickAlert.show(
                      context: context,
                      type: QuickAlertType.success,
                      title: "The Action was Successful",
                      text: "Subscribe to Proto Coders Point",
                      textColor: Colors.red,
                      autoCloseDuration: Duration(seconds: 2));
                },
                child: Text("Show Success"))
          ],
        ),
      ),
    );
  }
}

// flutter custom card button
Card buildButton({
  required onTap,
  required title,
  required text,
  required leadingIcon,
}) {
  return Card(
    shape: const StadiumBorder(),
    margin: const EdgeInsets.symmetric(
      horizontal: 20,
    ),
    clipBehavior: Clip.antiAlias,
    elevation: 1,
    child: ListTile(
      onTap: onTap,
      leading: leadingIcon,
      title: Text(title ?? ""),
      subtitle: Text(text ?? ""),
      trailing: const Icon(
        Icons.keyboard_arrow_right_rounded,
      ),
    ),
  );
}

Recommended Articles

Flutter Alert Dialog using RFlutter_alert package

Android Custom dialog box

Android Alert Box with list of menu options

Flutter rating dialog – redirect user to app store

Flutter Dart – How to use async await in loops example

0
How to use async await in loops
using await in for loop flutter

Hi Guy’s Welcome to Proto Coders Point. In this Flutter dart article, let’s checkout how to preform asynchronous operation in loops using async await and by using Future.forEach function.

Synchronous vs Asynchronous programming

  • synchronous: In simple words, When you execute code synchronously then you need to wait for it to finish task 1 before you move to task 2.
  • asynchronous: When you execute code asynchronously, then you can continue to execute the next task, no need to wait for the previous task to complete, but in case if task 1 & task 2 are related like, talk 2 get data from task 1 then you need to make use of async & await in a flutter.

Learn More about Flutter Future, Async & Await

Flutter await foreach – set duration between each loop iteration

Example 1: dart async for loops using Future.forEach function

The below code is a count down program, it will print numbers from 10 – 1 as listed in the array, After every print the program will wait for 1 second and then print the next iteration for the for loop.

In forEach loop I have make use of async await keywords to preform asynchronous operation with delay in loop.

// protocoderspoint.com
void main() async {
  final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  Iterable inReverse = items.reversed;
  await Future.forEach(inReverse, (item) async {
    print(item);
    await Future.delayed(const Duration(seconds: 1));
    // wait for 1 second before next iteration
  });
}

Example 2: using for in loop with async await

// protocoderspoint.com
void main() async {
  final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   Iterable inReverse = items.reversed;
  for (int item in inReverse) {
    print(item);
    await Future.delayed(const Duration(seconds: 1));
  }
}

Recommended Flutter dart articles

Dart Calculate product/multiplication on 2 number.

Print pattern star, number, character in dart.

Get sum of all values in map.