Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to add leading zeros to the shorter string of two strings in C#

2 Answers

0 votes
using System;

public class Program
{
	internal static string addToEmptyStr(string pad, int len) {
		string str = "";

		while (str.Length < len) {
			str += pad;
		}

		return str;
	}

	internal static string addLeadingZero(string str1, string str2) {
		int len1 = str1.Length;
		int len2 = str2.Length;

		string strToPad = "";

		int diff = Math.Abs(len1 - len2);

		if (diff > 0) {
			strToPad = addToEmptyStr("0", diff);
			if (len1 > len2) {
				strToPad += str2;
			}
			else {
				strToPad += str1;
			}
		}

		return strToPad;
	}

	public static void Main(string[] args)
	{
		string str1 = "123";
		string str2 = "8976753";

		if (str1.Length > str2.Length) {
			str2 = addLeadingZero(str1, str2);
		}
		else {
			str1 = addLeadingZero(str1, str2);
		}

		Console.WriteLine(str1);
		Console.WriteLine(str2);
	}
}



/*
run
 
0000123
8976753
 
*/

 



answered May 26, 2024 by avibootz
0 votes
using System;
 
public class Program
{
    internal static string addLeadingZero(string str1, string str2) {
        int len1 = str1.Length;
        int len2 = str2.Length;
 
        string strToPad = "";
 
        int diff = Math.Abs(len1 - len2);
 
        if (diff > 0) {
            strToPad = strToPad.PadLeft(diff, '0');
            if (len1 > len2) {
                strToPad += str2;
            }
            else {
                strToPad += str1;
            }
        }
 
        return strToPad;
    }
 
    public static void Main(string[] args)
    {
        string str1 = "123";
        string str2 = "8976753";
 
        if (str1.Length > str2.Length) {
            str2 = addLeadingZero(str1, str2);
        }
        else {
            str1 = addLeadingZero(str1, str2);
        }
 
        Console.WriteLine(str1);
        Console.WriteLine(str2);
    }
}
 
 
 
/*
run
  
0000123
8976753
  
*/

 



answered May 26, 2024 by avibootz

Related questions

...