Sum Up All characters of a string? - c#

Idea is simple, user enters the number(string) in a textbox, for example 155321, the app would the sum 1+5+5+3+2+1, and give out the sum of them, since i am still learning, i don't know where to start. The app is made in WPF. Hope my explanation is clear.

Simple LINQ answer:
string s = // your input string
var result = s.Select(x => int.Parse(x.ToString())).Sum();
This is the universal answer, without a dependence of WPF.

I propose two solution :
1- standard :
string resultNumber = "12"; // your number
int sumNumber = 0;// result of calculating
for (int i = 0; i < resultNumber.Length; i++)
{
sumNumber = int.Parse(resultNumber.Substring(i, 1)) + sumNumber;
}
2- Recursive
public static int SumNumber(string number)
{
if(string.IsNullOrEmpty(number))
return 0;
else if(number.Length == 1)
return int.Parse(number);
else
return SumNumber(number.Substring(1)) + int.Parse(number.Substring(0, 1));
}

The cleanest solution is as follows:
var str = "19035683";
var sum = str.Sum(x => char.GetNumericValue(x));
Another similar solution is:
var str = "12312512341231";
var sum = str.Sum(x => x - '0');

Related

count the number of points at the end of a string

I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.
How can this be done?
string sample = "This.is.a.sample.string.....";
for the example above the correct answer would be 5 because there are 5 points at the end of the string.
because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions
\.*$
should be used in such a case.
Start from the end of the string and go back char by char until its not a dot:
string sample = "This.is.a.sample.string....."
int count = 0;
for (int i = sample.Length - 1; i >= 0; i--)
{
if (sample[i] != '.') break;
count++;
}
Using Linq:
var test = "this.is.a.test........";
var count = test.ToCharArray().Reverse().TakeWhile(q => q == '.').Count();
Convert string to array, reverse, then take while character = '.'. Count result.
A simple solution using an extension method.
var test = "this.is.a.test........";
Console.WriteLine(test.CountTrailingDots());
public static int CountTrailingDots(this string value)
{
return value.Length - value.TrimEnd('.').Length;
}
Using Regex:
int points = Regex.Match("This.is.a.sample.string....", #"^[\w\W]*?([.]*+)$").Groups[1].Value.Length;
Description:
*+ = Matches as many characters as possible
*? = Matches as few characters as possible.
It can be something like..
string sample = "This.is.a.sample.string.....";
int count = 0;
if(sample.EndsWith("."))
count = sample.Substring(sample.TrimEnd('.').Length).Length;

Calculate number of zeros in a string

I have a string as follow 51200000000000000000000000000000
This string is not fixed. It will be appended depends on the number of boards. If there are two boards, the string will be as follow 5120000000000000000000000000000052200000000000000000000000000000
I would like to know how to calculate the number of zeros in the string.
I'm using the following code but it is not flexible if there are more than two boards.
string str = "51200000000000000000000000000000";
string zeros = "00000000000000000000000000000";
if (str.Contains(zeros))
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
You can use the following piece of code to do this, which will give you the number of zeros(Example).
char matchChar='0';
string strInput = "51200000000000000000000000000000";
int zeroCount = strInput.Count(x => x == matchChar); // will be 29
You can do the same by iterating through each characters and check whether it is the required character(say 0) then take its count.
Use a simple foreach loop to traverse the string and count:
int CountZeroes(string str)
{
// TODO: error checking, etc.
int count = 0;
foreach (var character in str)
{
if (character == '0') count++;
}
return count;
}
a little advanced (or so) technique would be to convert the string to char array then to list of chars then using LINQ
string str = "51200000000000000000000000000000";
List<char> nums = str.ToCharArray().ToList();
Console.WriteLine(nums.Where(x => x.Equals('0')).Select(x => x.ToString()).Count());
i just placed this here in case you want to learn not just a single approach :)
It can also do with a for loop and Substring.
Code
string str = "51200000000000000000000000000000";
int n = 0;
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == "0")
n += 1;
}
Console.WriteLine("Count : " + n.ToString());
Working fiddle demo
Code:
string st;
st = textBox1.Text;
int countch = 0, i;
for (i = 0; i < st.Length; i++)
if (st[i]=='0') countch++;
MessageBox.Show(countch.ToString());
using System.Linq
int count0s = str.Count(z => z == '0');
will return how many 0's in your str string

C# "Version-Updater"

I want to increase the last number of the version (for Example: 1.0.0.0 -> 1.0.0.1).
I would prefer to kep this code :)
The actuall code looks like that:
private void UpdateApplicationVersion(string filepath)
{
string currentApplicationVersion = "1.2.3.4"
string newApplicationVersionDigit = ((currentApplicationVersion.Split('.')[3]) + 1).ToString();
string newApplicatonVersion = string.Empty;
for (int i = 0; i <= currentApplicationVersion.Length; i++)
{
if (i == 7)
{
newApplicatonVersion += newApplicationVersionDigit ;
}
else
{
newApplicatonVersion += currentApplicationVersion.ToCharArray()[i];
}
}
Do it simple way,
string v1 = "1.0.0.1";
string v2 = "1.0.0.4";
var version1 = new Version(v1);
var version2 = new Version(v2);
var result = version1.CompareTo(version2);
if (result > 0)
Console.WriteLine("version1 is greater");
else if (result < 0)
Console.WriteLine("version2 is greater");
else
Console.WriteLine("versions are equal");
I think it could be done by parsing all components of the version, manipulate the last one and put them together again as follows.
string[] Components = currentApplicationVersion.Split('.');
int Maj = Convert.ToInt32(Components[0]);
int Min = Convert.ToInt32(Components[1]);
int Revision = Convert.ToInt32(Components[2]);
int Build = Convert.ToInt32(Components[3]);
Build++;
string newApplicationVersion
= string.Format("{0}.{1}.{2}.{3}", Maj, Min, Revision, Build);
You can try Split and Join:
string currentApplicationVersion = "1.2.3.4";
int[] data = currentApplicationVersion.Split('.')
.Select(x => int.Parse(x, CultureInfo.InvariantCulture))
.ToArray();
// The last version component is data[data.Length - 1]
// so you can, say, increment it, e.g.
data[data.Length - 1] += 1;
// "1.2.3.5"
String result = String.Join(".", data);
There's a class build for working with version numbers. It's called Version and can be found in the System namespace
you can parse your current version by passing the string representing the version to the constructor
var currentApplicationVersion = new Version(currentApplicationVersionString);
and then get the new one with another of the constructors
var newApplicationVersion = new Version(
currentApplicationVersion.Major,
currentApplicationVersion.Minor,
currentApplicationVersion.Build,
currentApplicationVersion.Revision +1
);
and then simply call .ToString() if you need it as a string

How to Parse a String with Multiple Decimal Points

I was wanting to parse a string such as "10.0.20" into a number in order to compare another string with the same format in C#.net
For example I would be comparing these two numbers to see which is lesser than the other:
if (10.0.30 < 10.0.30) ....
I am not sure which parsing method I should use for this, as decimal.Parse(string) didn't work in this case.
Thanks for your time.
Edit: #Romoku answered my question I never knew there was a Version class, it's exactly what I needed. Well TIL. Thanks everyone, I would have spent hours digging through forms if it wasn't for you lot.
The the string you're trying to parse looks like a verson, so try using the Version class.
var prevVersion = Version.Parse("10.0.20");
var currentVersion = Version.Parse("10.0.30");
var result = prevVersion < currentVersion;
Console.WriteLine(result); // true
Version looks like the easiest way, however, if you need unlimited 'decimal places' then try the below
private int multiDecCompare(string str1, string str2)
{
try
{
string[] split1 = str1.Split('.');
string[] split2 = str2.Split('.');
if (split1.Length != split2.Length)
return -99;
for (int i = 0; i < split1.Length; i++)
{
if (Int32.Parse(split1[i]) > Int32.Parse(split2[i]))
return 1;
if (Int32.Parse(split1[i]) < Int32.Parse(split2[i]))
return -1;
}
return 0;
}
catch
{
return -99;
}
}
Returns 1 if first string greater going from left to right, -1 if string 2, 0 if equal and -99 for an error.
So would return 1 for
string str1 = "11.30.42.29.66";
string str2 = "11.30.30.10.88";

Char/String comparison

I'm trying to have a suggestion feature for the search function in my program eg I type janw doe in the search section and it will output NO MATCH - did you mean jane doe? I'm not sure what the problem is, maybe something to do with char/string comparison..I've tried comparing both variables as type char eg char temp -->temp.Contains ...etc but an error appears (char does not contain a definition for Contains). Would love any help on this! 8)
if (found == false)
{
Console.WriteLine("\n\nMATCH NOT FOUND");
int charMatch = 0, charCount = 0;
string[] checkArray = new string[26];
//construction site /////////////////////////////////////////////////////////////////////////////////////////////////////////////
for (int controlLoop = 0; controlLoop < contPeople.Length; controlLoop++)
{
foreach (char i in userContChange)
{
charCount = charCount + 1;
}
for (int i = 0; i < userContChange.Length; )
{
string temp = contPeople[controlLoop].name;
string check=Convert.ToString(userContChange[i]);
if (temp.Contains(check))
{
charMatch = charMatch + 1;
}
}
int half = charCount / 2;
if (charMatch >= half)
{
checkArray[controlLoop] = contPeople[controlLoop].name;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
Console.WriteLine("Did you mean: ");
for (int a = 0; a < checkArray.Length; a++)
{
Console.WriteLine(checkArray[a]);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
A string is made up of many characters. A character is a primitive, likewise, it doesn't "contain" any other items. A string is basically an array of characters.
For comparing string and characters:
char a = 'A';
String alan = "Alan";
Debug.Assert(alan[0] == a);
Or if you have a single digit string.. I suppose
char a = 'A';
String alan = "A";
Debug.Assert(alan == a.ToString());
All of these asserts are true
But, the main reason I wanted to comment on your question, is to suggest an alternative approach for suggesting "Did you mean?". There's an algorithm called Levenshtein Distance which calculates the "number of single character edits" required to convert one string to another. It can be used as a measure of how close two strings are. You may want to look into how this algorithm works because it could help you.
Here's an applet that I found which demonstrates: Approximate String Matching with k-differences
Also the wikipedia link Levenshtein distance
Char type cannot have .Contains() because is only 1 char value type.
In your case (if i understand), maybe you need to use .Equals() or the == operator.
Note: for compare String correctly, use .Equals(),
the == operator does not work good in this case because String is reference type.
Hope this help!
char type dosen't have the Contains() method, but you can use iit like this: 'a'.ToString().Contains(...)
if do not consider the performance, another simple way:
var input = "janw doe";
var people = new string[] { "abc", "123", "jane", "jane doe" };
var found = Array.BinarySearch<string>(people, input);//or use FirstOrDefault(), FindIndex, search engine...
if (found < 0)//not found
{
var i = input.ToArray();
var target = "";
//most similar
//target = people.OrderByDescending(p => p.ToArray().Intersect(i).Count()).FirstOrDefault();
//as you code:
foreach (var p in people)
{
var count = p.ToArray().Intersect(i).Count();
if (count > input.Length / 2)
{
target = p;
break;
}
}
if (!string.IsNullOrWhiteSpace(target))
{
Console.WriteLine(target);
}
}

Categories

Resources