Adding numbers to a string? - c#

I have strings that look like "01", "02". Is there an easy way that I can change the string into a number, add 1 and then change it back to a string so that these strings now look like "02", "03" etc. I'm not really good at C# as I just started and I have not had to get values before.

To get from a string to an integer, you can youse int.Parse():
int i = int.Parse("07");
To get back into a string with a specific format you can use string.Format():
strings = string.Format("{0:00}",7);
The latter should give "07" if I understand http://www.csharp-examples.net/string-format-int/ correctly.

You can convert the string into a number using Convert.ToInt32(), add 1, and use ToString() to convert it back.
int number = Convert.ToInt32(originalString);
number += 1;
string newString = number.ToString();

Parse the integer
int i = int.Parse("07");
add to your integer
i = i + 1;
make a new string variable and assign it to the string value of that integer
string newstring = i.ToString();

AddStringAndInt(string strNumber, int intNumber)
{
//TODO: Add error handling here
return string.Format("{0:00}", (int.TryParse(strNumber) + intNumber));
}

static string StringsADD(string s1, string s2)
{
int l1 = s1.Count();
int l2 = s2.Count();
int[] l3 = { l1, l2 };
int minlength = l3.Min();
int maxlength = l3.Max();
int komsu = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxlength; i++)
{
Int32 e1 = Convert.ToInt32(s1.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 e2 = Convert.ToInt32(s2.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
Int32 sum = e1 + e2 + komsu;
if (sum >= 10)
{
sb.Append(sum - 10);
komsu = 1;
}
else
{
sb.Append(sum);
komsu = 0;
}
if (i == maxlength - 1 && komsu == 1)
{
sb.Append("1");
}
}
return new string(sb.ToString().Reverse().ToArray());
}
I needed to add huge numbers that are 1000 digit. The biggest number type in C# is double and it can only contain up to 39 digits. Here a code sample for adding very huge numbers treating them as strings.

Related

I'm trying to get sum of digits from a number, Where Is the Mistake? [duplicate]

This question already has answers here:
Sum of digits in C#
(18 answers)
Closed 1 year ago.
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for(int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber[i]);
}
Console.WriteLine(Sum);
it should show 3, But instead its showing 99.
What is actual mistake.
If you iterate the characters in a string, you'll get chars. The problem is that converting a char to an int with Convert.ToInt32(), will result in the ASCII Unicode UTF-16 value of that char.
The ASCII Unicode UTF-16 value of '1' = 49 and for '2' is 50 which sums 99.
You should make it a string first.
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for(int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber[i].ToString());
}
Console.WriteLine(Sum);
The problem is that Convert.ToInt32(sNumber[i]) is getting the numeric value of the character at position i, i.e. Convert.ToInt32('1') gives 49. Note that this value is a char and therefore Convert.ToInt32('1') returns the value of the UTF-16 character.
Why convert it to a string when plain mathematics will do what you want.
int number = 12;
int sum = 0;
while (number > 0){
sum += number % 10;
number /= 10; // Integer division
}
Console.WriteLine(sum);
Convert.ToNumber(char) returns code of character in ASCII. In your example 1 have code 49 and 2 have code 50. 49 + 50 results in 99
You need to use Sum = Sum + int.Parse(sNumber[i].ToString()) to get actual value of digit
no need to convert to string for this. Use simple mathematics.
int Number = 123;
int Sum = 0;
while (Number != 0)
{
Sum += (Number % 10);
Number = Number / 10;
}
System.Console.WriteLine(Sum);
Since it hasn't been posted, here's a simple one-liner using Linq:
int Sum = Number.ToString().Sum(x => (int)char.GetNumericValue(x));
Change it to the following:
int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for (int i = 0; i < sNumber.Length; i++)
{
Sum = Sum + Convert.ToInt32(sNumber.Substring(i,1));
}
Console.WriteLine(Sum);
Use Substring instead of []
Convert.ToInt32(char x) will give you the UTF16 value of the char.
See: https://learn.microsoft.com/de-de/dotnet/api/system.convert.toint32?view=net-5.0#System_Convert_ToInt32_System_Char_

How can I combine two strings and create sets by 4 characters, two coming from one string and other two from other string? c#

I got stuck in creating an algorithm that creates sets of 4 characters from two strings, two characters from one string and two from other string.
Example:
String one: FIRSTNAME
String two: LASTNAME
and the result that I expect is to get 10 sets of 4 characters like this: FILA, RSST, TNNA, AMME, EFLA and so on until we get 10 combinations like this.
this is the code that I made
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Name");
string name = Console.ReadLine();
Console.WriteLine("Lastname");
string lastname = Console.ReadLine();
int i;
var nchars = name.ToCharArray();
var pchars = lastname.ToCharArray();
for (i = 0; i <= 10; i++){
int ctr0;
int ctr;
int ctr2;
for (ctr = 0, ctr2 = 1, ctr0 = 1;
ctr < 10;
ctr0++, ctr = ctr + 2, ctr2 = ctr2 + 2) {
Console.WriteLine("{0}{1}{2}{3}{4}",
ctr0,
nchars[ctr],
nchars[ctr2],
pchars[ctr],
pchars[ctr2]);
}
}
}
}
and the output is good so far because I get
1FILA
2RSST
3TNNA
4AMME
but it stops when the string ends and instead of getting 10 combinations I get only 4.. what can I do?
Am I doing it wrong?
Or adding some Enumerable love.
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Name");
string name = Console.ReadLine();
Console.WriteLine("Lastname");
string lastname = Console.ReadLine();
// set the number of required sets and size
const int sets = 10;
const int size = 2;
// make both inputs long enough
var input1 = string.Concat(Enumerable.Repeat(name, (Math.Abs((sets * size) / name.Length) + 1)));
var input2 = string.Concat(Enumerable.Repeat(lastname, (Math.Abs((sets * size) / lastname.Length) + 1)));
// enumerate the index so we can substring the inputs.
var results = Enumerable.Range(0, sets)
.Select(x => $"{x + 1}{input1.Substring(x * size, size)}{input2.Substring(x * size, size)}");
// optional write to console
foreach(var result in results)
{
Console.WriteLine(result);
}
}
}
Trying to rectify your alogrithm, I think this is what you should try:
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Name");
string name = "FIRSTNAME";
Console.WriteLine("Lastname");
string lastname = "LASTNAME";
int i;
var nchars = name.ToCharArray();
var pchars = lastname.ToCharArray();
var ncharsCount = nchars.Length;
var pcharsCount = pchars.Length;
//for (i=0;i<=10;i++){
int ctr0;
int ctr;
int ctr2;
for (ctr = 0, ctr2 = 1, ctr0=1; ctr0 < 10 ;ctr0++, ctr++,ctr2++){
Console.WriteLine("{0}{1}{2}{3}{4}", ctr0,nchars[ctr%ncharsCount],nchars[ctr2%ncharsCount],pchars[ctr%pcharsCount],pchars[ctr2%pcharsCount]);
}
//}
}
}
Let's split the initial problem into several easier ones:
CircularSubstring, e.g. for value = "12345", index = 4, length = 3 we get "512"
MyGemerator which generate "FILA", "RSST" etc.
Final output in the required format
Code:
private static String CircularSubstring(string value, int index, int length) {
StringBuilder sb = new StringBuilder(length);
// + + value.Length) % value.Length -
// .Net can return negative remainder when we want it to be in [0..value.Length)
for (int i = 0; i < length; ++i)
sb.Append(value[((index + value.Length + i) % value.Length + value.Length) % value.Length]);
return sb.ToString();
}
private static IEnumerable<string> MyGenerator(string left, string right, int size) {
for (int i = 0; ; i += size)
yield return CircularSubstring(left, i, size) + CircularSubstring(right, i, size);
}
Then we are ready to generate a report in required format:
string one = "FIRSTNAME";
string two = "LASTNAME";
int size = 2; // chunks of size 2 from each (one, two) strings
int take = 10; // 10 chunks to generate
string report = string.Join(Environment.NewLine, MyGenerator(one, two, size)
.Take(take)
.Select((item, index) => $"{index + 1}{item}")
);
Console.Write(report);
Outcome:
1FILA
2RSST
3TNNA
4AMME
5EFLA
6IRST
7STNA
8NAME
9MELA
10FIST
More demo:
Console.Write(string.Join(Environment.NewLine, MyGenerator("Stack", "Overflow", 3)
.Take(12)
.Select((item, index) => $"{index + 1,2}. {item}")
));
Outcome:
1. StaOve
2. ckSrfl
3. tacowO
4. kStver
5. ackflo
6. StawOv
7. ckSerf
8. taclow
9. kStOve
10. ackrfl
11. StaowO
12. ckSver

Converting number to comma separated values

I need to convert numbers into a comma separated format to display in C#.
For Example:
1000 to 1,000
45000 to 45,000
150000 to 1,50,000
21545000 to 2,15,45,000
How to achieve this in C#?
I tried the below code:
int number = 1000;
number.ToString("#,##0");
But it is not working for lakhs.
I guess you can do this by creating a custom number format info for your needs
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
// you are interested in this part of controlling the group sizes
nfo.CurrencyGroupSizes = new int[] { 3, 2 };
nfo.CurrencySymbol = "";
Console.WriteLine(15000000.ToString("c0", nfo)); // prints 1,50,00,000
if specifically only for numbers then you could also do
nfo.NumberGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };
Console.WriteLine(15000000.ToString("N0", nfo));
Here's a similar thread to yours add commas in thousands place for a number
and here's the solution that worked perfectly for me
String.Format("{0:n}", 1234);
String.Format("{0:n0}", 9876); // no decimals
If you want to be unique and do extra work that you don't have to here is a function I created for integer numbers you can place commas at whatever interval you want, just put 3 for a comma for each thousandths or you could alternatively do 2 or 6 or whatever you like.
public static string CommaInt(int Number,int Comma)
{
string IntegerNumber = Number.ToString();
string output="";
int q = IntegerNumber.Length % Comma;
int x = q==0?Comma:q;
int i = -1;
foreach (char y in IntegerNumber)
{
i++;
if (i == x) output += "," + y;
else if (i > Comma && (i-x) % Comma == 0) output += "," + y;
else output += y;
}
return output;
}
Have you tried:
ToString("#,##0.00")
Quick and dirty way:
Int32 number = 123456789;
String temp = String.Format(new CultureInfo("en-IN"), "{0:C0}", number);
//The above line will give Rs. 12,34,56,789. Remove the currency symbol
String indianFormatNumber = temp.Substring(3);
An easy solution would be to pass a format into the ToString() method:
string format = "$#,##0.00;-$#,##0.00;Zero";
decimal positiveMoney = 24508975.94m;
decimal negativeMoney = -34.78m;
decimal zeroMoney = 0m;
positiveMoney.ToString(format); //will return $24,508,975.94
negativeMoney.ToString(format); //will return -$34.78
zeroMoney.ToString(format); //will return Zero
Hope this helps,

Masking all characters of a string except for the last n characters

I want to know how can I replace a character of a string with condition of "except last number characters"?
Example:
string = "4111111111111111";
And I want to make it that
new_string = "XXXXXXXXXXXXX1111"
In this example I replace the character to "X" except the last 4 characters.
How can I possibly achieve this?
Would that suit you?
var input = "4111111111111111";
var length = input.Length;
var result = new String('X', length - 4) + input.Substring(length - 4);
Console.WriteLine(result);
// Ouput: XXXXXXXXXXXX1111
How about something like...
new_string = new String('X', YourString.Length - 4)
+ YourString.Substring(YourString.Length - 4);
create a new string based on the length of the current string -4 and just have it all "X"s. Then add on the last 4 characters of the original string
Here's a way to think through it. Call the last number characters to leave n:
How many characters will be replaced by X? The length of the string minus n.
How can we replace characters with other characters? You can't directly modify a string, but you can build a new one.
How to get the last n characters from the original string? There's a couple ways to do this, but the simplest is probably Substring, which allows us to grab part of a string by specifying the starting point and optionally the ending point.
So it would look something like this (where n is the number of characters to leave from the original, and str is the original string - string can't be the name of your variable because it's a reserved keyword):
// 2. Start with a blank string
var new_string = "";
// 1. Replace first Length - n characters with X
for (var i = 0; i < str.Length - n; i++)
new_string += "X";
// 3. Add in the last n characters from original string.
new_string += str.Substring(str.Length - n);
This might be a little Overkill for your ask. But here is a quick extension method that does this.
it defaults to using x as the masking Char but can be changed with an optional char
public static class Masking
{
public static string MaskAllButLast(this string input, int charsToDisplay, char maskingChar = 'x')
{
int charsToMask = input.Length - charsToDisplay;
return charsToMask > 0 ? $"{new string(maskingChar, charsToMask)}{input.Substring(charsToMask)}" : input;
}
}
Here a unit tests to prove it works
using Xunit;
namespace Tests
{
public class MaskingTest
{
[Theory]
[InlineData("ThisIsATest", 4, 'x', "xxxxxxxTest")]
[InlineData("Test", 4, null, "Test")]
[InlineData("ThisIsATest", 4, '*', "*******Test")]
[InlineData("Test", 16, 'x', "Test")]
[InlineData("Test", 0, 'y', "yyyy")]
public void Testing_Masking(string input, int charToDisplay, char maskingChar, string expected)
{
//Act
string actual = input.MaskAllButLast(charToDisplay, maskingChar);
//Assert
Assert.Equal(expected, actual);
}
}
}
StringBuilder sb = new StringBuilder();
Char[] stringChar = string.toCharArray();
for(int x = 0; x < stringChar.length-4; x++){
sb.append(stringChar[x]);
}
sb.append(string.substring(string.length()-4));
string = sb.toString();
I guess you could use Select with index
string input = "4111111111111111";
string new_string = new string(input.Select((c, i) => i < input.Length - 4 ? 'X' : c).ToArray());
Some of the other concise answers here did not account for strings less than n characters. Here's my take:
var length = input.Length;
input = length > 4 ? new String('*', length - 4) + input.Substring(length - 4) : input;
lui,
Please Try this one...
string dispString = DisplayString("4111111111111111", 4);
Create One function with pass original string and no of digit.
public string DisplayString(string strOriginal,int lastDigit)
{
string strResult = new String('X', strOriginal.Length - lastDigit) + strOriginal.Substring(strOriginal.Length - lastDigit);
return strResult;
}
May be help you....
Try this:
String maskedString = "...."+ (testString.substring(testString.length() - 4, testString.length()));
Late to the party but I also wanted to mask all but the last 'x' characters, but only mask numbers or letters so that any - ( ), other formatting, etc would still be shown. Here's my quick extension method that does this - hopefully it helps someone. I started with the example from Luke Hammer, then changed the guts to fit my needs.
public static string MaskOnlyChars(this string input, int charsToDisplay, char maskingChar = 'x')
{
StringBuilder sbOutput = new StringBuilder();
int intMaskCount = input.Length - charsToDisplay;
if (intMaskCount > 0) //only mask if string is longer than requested unmasked chars
{
for (var intloop = 0; intloop < input.Length; intloop++)
{
char charCurr = Char.Parse(input.Substring(intloop, 1));
byte[] charByte = Encoding.ASCII.GetBytes(charCurr.ToString());
int intCurrAscii = charByte[0];
if (intloop <= (intMaskCount - 1))
{
switch (intCurrAscii)
{
case int n when (n >= 48 && n <= 57):
//0-9
sbOutput.Append(maskingChar);
break;
case int n when (n >= 65 && n <= 90):
//A-Z
sbOutput.Append(maskingChar);
break;
case int n when (n >= 97 && n <= 122):
//a-z
sbOutput.Append(maskingChar);
break;
default:
//Leave other characters unmasked
sbOutput.Append(charCurr);
break;
}
}
else
{
//Characters at end to remain unmasked
sbOutput.Append(charCurr);
}
}
}
else
{
//if not enough characters to mask, show unaltered input
return input;
}
return sbOutput.ToString();
}

Need code for addition of 2 numbers

I am having the numbers follows taken as strings
My actual number is 1234567890123456789
from this i have to separate it as s=12 s1=6789 s3=3456789012345
remaining as i said
I would like to add as follows
11+3, 2+4, 6+5, 7+6, 8+7, 9+8 such that the output should be as follows
4613579012345
Any help please
public static string CombineNumbers(string number1, string number2)
{
int length = number1.Length > number2.Length ? number1.Length : number2.Length;
string returnValue = string.Empty;
for (int i = 0; i < length; i++)
{
int n1 = i >= number1.Length ? 0 : int.Parse(number1.Substring(i,1));
int n2 = i >= number2.Length ? 0 : int.Parse(number2.Substring(i,1));
int sum = n1 + n2;
returnValue += sum < 10 ? sum : sum - 10;
}
return returnValue;
}
This sounds an awful lot like a homework problem, so I'm not giving code. Just think about what you need to do. You are saying that you need to take the first character off the front of two strings, parse them to ints, and add them together. Finally, take the result of the addition and append them to the end of a new string. If you write code that follows that path, it should work out fine.
EDIT: As Ralph pointed out, you'll also need to check for overflows. I didn't notice that when I started typing. Although, that shouldn't be too hard, since you're starting with a two one digit numbers. If the number is greater than 9, then you can just subtract 10 to bring it down to the proper one digit number.
How about this LINQish solution:
private string SumIt(string first, string second)
{
IEnumerable<char> left = first;
IEnumerable<char> right = second;
var sb = new StringBuilder();
var query = left.Zip(right, (l, r) => new { Left = l, Right = r })
.Select(chars => new { Left = int.Parse(chars.Left.ToString()),
Right = int.Parse(chars.Right.ToString()) })
.Select(numbers => (numbers.Left + numbers.Right) % 10);
foreach (var number in query)
{
sb.Append(number);
}
return sb.ToString();
}
Tried something:
public static string NumAdd(int iOne, int iTwo)
{
char[] strOne = iOne.ToString().ToCharArray();
char[] strTwo = iTwo.ToString().ToCharArray();
string strReturn = string.Empty;
for (int i = 0; i < strOne.Length; i++)
{
int iFirst = 0;
if (int.TryParse(strOne[i].ToString(), out iFirst))
{
int iSecond = 0;
if (int.TryParse(strTwo[i].ToString(), out iSecond))
{
strReturn += ((int)(iFirst + iSecond)).ToString();
}
}
// last one, add the remaining string
if (i + 1 == strOne.Length)
{
strReturn += iTwo.ToString().Substring(i+1);
break;
}
}
return strReturn;
}
You should call it like this:
string strBla = NumAdd(12345, 123456789);
This function works only if the first number is smaller than the second one. But this will help you to know how it is about.
In other words, you want to add two numbers treating the lesser number like it had zeroes to its right until it had the same amount of digits as the greater number.
Sounds like the problem at this point is simply a matter of finding out how much you need to multiply the smaller number by in order to reach the number of digits of the larger number.

Categories