Apply a math function on all integers value of two strings - c#

Two strings are given. I want to apply a math function on each number in the strings and save it in new string. Rules:
"19834675"; // keypc
"28374651";// keyserial
(1)sb[0]=max(keypc[0],keyserial[0]) the first element of final string
max(1,2)=2 1 is first of"19834675" , 2 is first of "28374651"
(2)sb[1]=Math.Floor((keypc[1]+keyserial[1])/3) the second element of final string //
(3)sb[2]= (keypc[1]+keyserial[1]) The remainder is divided by 10
8+3=11---->1 , 8 is the third char of "19834675" and 3 the third char of "28374651"
My try for (1):
I used the following code for (1)
string keypc ="19834675";
string keyserial="28374651";
StringBuilder sb = new StringBuilder(keypc,keypc.Length);
if (sbkeypc[0] < sbkeyserial[0])
{
sb[0] = sbkeyserial[0];
}else
{
sb[0] = sbkeypc[0];
}
My try for (2):The question is why the following code does not work?!
and How to do (3)?
double inttemp=Math.Floor((Char.GetNumericValue(keypc[1])+Char.GetNumericValue(keyserial[1]))/3);
sb[1]= Convert.ToChar(Convert.ToInt32(inttemp));
Console.WriteLine(Convert.ToChar(Convert.ToInt32(inttemp))); // error here --->return ""
Console.WriteLine(sb.ToString()); // error here: the length of sb reduced

I think this is what you want:
You can see it in action here
using System;
using System.Text;
public class Program
{
public static void Main()
{
string keypc = "19834675";
string keyserial = "28374651";
StringBuilder sb = new StringBuilder(keypc, keypc.Length);
sb[0] = MinChar(keypc[0], keyserial[0]);
sb[1] = FloorChar(keypc[1], keyserial[1]);
for (int i=2; i<keypc.Length; i++)
{
sb[i] = RemainderChar(keypc[i], keyserial[i]);
}
Console.WriteLine(sb.ToString());
}
public static char MinChar(char c1, char c2)
{
double val1 = Char.GetNumericValue(c1);
double val2 = Char.GetNumericValue(c2);
double val3 = Math.Min(val1, val2);
string str = val3.ToString();
return str[0];
}
public static char FloorChar(char c1, char c2)
{
double val1 = Char.GetNumericValue(c1);
double val2 = Char.GetNumericValue(c2);
double val3 = Math.Floor((val1+val2)/3);
string str = val3.ToString();
return str[0];
}
public static char RemainderChar(char c1, char c2)
{
double val1 = Char.GetNumericValue(c1);
double val2 = Char.GetNumericValue(c2);
Console.WriteLine("{0} {1}", val1, val2);
double val3 = (val1+val2) % 10;
Console.WriteLine("" + val3);
string str = val3.ToString();
return str[0];
}
}

Related

C#. How do I write a function that can search a string within a string and return the number of occurrences? [duplicate]

This question already has answers here:
How would you count occurrences of a string (actually a char) within a string?
(34 answers)
Closed 6 years ago.
I need some help figure this one out. I need to search a string within a string and return the number of occurrences. I have tried the code below and it works and i also tried to use a regex and it worked but my teacher said to pretend that i can't use the indexOf or the regex. I know there have been some similar questions but that didn't help me much since they all use IndexOf or regex. So any ideas please?
What I have tried:
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string s1 = "hellohjhghello";
string s2 = "he";
var r = Occurrences(s1, s2);
Console.WriteLine("{0} is repeated {1} times", s2, r);
}
static int Occurrences(string s1, string s2)
{
int count = 0;
int pos = 0;
while((pos = s1.IndexOf(s2,pos)) > -1)
{
count++;
pos += s2.Length;
}
return count;
}
}
}
EDIT:
I don't know what my teacher expects me to so but in another exercise I did a search for a char in string. He said to do something similar but for a string. My previous exercise goes like this:
class ex3
{
static void Main(string[] args)
{
string str = "aaabekldfj";
char letter = 'a';
var r = Occurrences(str, letter);
Console.WriteLine("The letter '{0}' from string '{1}' has {2} occurrences", letter, str,r);
}
static int Occurences(string str, char letter)
{
int repeat = 0;
for(int i=0; i< str.Length; i++)
{
if (str[i] == letter)
repeat++;
}
return repeat;
}
}
Why not keep it simple?
string compareText = "hello! This is a string to check hello's in this string!";
string compareWord = "hello";
int occurrences = (compareText.Length - compareText.Replace(compareWord, string.Empty).Length) / compareWord.Length;
Without indexof and regex and keeping it simple (but not fast), you can do following
static int OccurrencesAdvanced(string s1, string s2)
{
var result = 0;
for (var i = 0; i <= (s1.Length - s2.Length); i++)
{
var tested = s1.Substring(i, s2.Length);
if (string.Compare(tested, s2) == 0)
{
i += Math.Max(1, s2.Length - 1);
result++;
}
}
return result;
}
Here is my idea what first came in my mind. I don't know currently where are you in your studies so this solution might not good for you.
class Program
{
static void Main(string[] args)
{
var s1 = "hellohjhghello";
var s2 = "lo";
var occurence = 0;
Occurrences(s1, s2, ref occurence);
Console.WriteLine("{0} is repeated {1} times", s2, occurence);
Console.ReadLine();
}
static void Occurrences(string s1, string s2, ref int occurence)
{
var index = s1.IndexOf(s2);
if (index > -1)
{
occurence++;
s1 = s1.Substring(index + s2.Length);
Occurrences(s1, s2, ref occurence);
}
}
}

add operation to string in my own language

I have a word of 5 character like:
"AD5B6" , "1G2H0" , "HASAN" , "ABC5Z" , "1ZZZZ"
I need the new value when i add "1" to my word (like counting system) so the result will be like:
"AD5B7" , "1G2H1" , "HASAO" , "ABC60" , "20000"
I write the code for that but i have the problem in 'Z' character due to i need to increment the previous value.
my C# code is:
public string Get(string h)
{
var lang = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string hash = h.ToUpper();
char c = hash[hash.Length - 1]; // last char in the word
string result = "";
for (int i = 0; i < lang.Length; i++)
{
if (c == lang[i] && c != 'Z')
{
char cc = lang[i + 1]; // last char + 1
string s1 = hash.Split(c)[0];
string s2 = hash.Split(c)[1];
result = s1 + cc + s2;
break;
}
else
{ // the wrong in this code and i think i should do it in recursive way
char cc = '0';
string s1 = hash.Split(c)[0];
char s11 = s1[s1.Length - 1];
string s2 = hash.Split(c)[1];
result = s1 + cc + s2;
break;
}
}
return result;
}
Seems like you want to do Base36 operations like
var base36 = new BaseN("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("AD5B7") + 1) );
Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("1ZZZZ") + 1) );
Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("ZZZZZ") + 1));
Console.WriteLine( base36.ToBaseNString(base36.FromBaseNString("6ZZZZZZZZZZZZZZZZZZ") + 1) );
Console.WriteLine(base36.ToBaseNString(base36.FromBaseNString("123") * 2));
A generic alogorithm for any charset can be written as
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
public class BaseN
{
List<char> CHARSET = null;
public BaseN(string charset)
{
CHARSET = new List<char>(charset);
}
public String ToBaseNString(BigInteger input)
{
var stack = new Stack<char>();
while (input != 0)
{
stack.Push(CHARSET[(int)(input % CHARSET.Count)]);
input /= CHARSET.Count;
}
return new string(stack.ToArray());
}
public BigInteger FromBaseNString(string input)
{
BigInteger sum = 0;
int i = 0;
foreach (char c in input.Reverse())
{
sum += CHARSET.IndexOf(c) * BigInteger.Pow(CHARSET.Count, i++);
}
return sum;
}
}
Although, there are better ways to do bitwise operations in c#, you can also do it as:
var base2 = new BaseN("01");
Console.WriteLine( base2.ToBaseNString(base2.FromBaseNString("11") *3 ) );

Parse String to Generate Output String in Specific Format

I am looking to generate a Sequence Number in this format
00000A
00000B
00000B
and so on till
00000Z
and then
00001A
00001B
00001C
...
00001Z
...
00010A
till
99999Z
I know that I can generate Max 2.6 million rows using this method but I guess that is enough
so, if I have the a String, lets say 26522C, Now i want the next number as 26522D
or If I have 34287Z, i want 34288A
I can write the Algorithm about it but there will be lots of parsing of the input string characters by characters
I was wondering is there any easier way of doing it
String GetNextNumberInSequence(String inputString)
{
if (inputString.Length == 6)
{
var charArray = inputString.ToCharArray();
char[] inputChars = { charArray[0], charArray[1], charArray[2],charArray[3],charArray[4],charArray[5] };
if(Char.IsDigit(charArray[5]))
{
//Parse first 5 characters
}
}
}
private static String GetNextNumberInSequence(String inputString)
{
var integerpart = int.Parse(inputString.Substring(0, 5));
var characterPart = inputString[5];
if (characterPart == 'Z')
return string.Format("{0}{1}", (++integerpart).ToString("D5"), "A");
var nextChar = (char)(characterPart + 1);
return string.Format("{0}{1}", (integerpart).ToString("D5"), nextChar.ToString());
}
You can achieve this by converting a number to Base36.
Take a look at this sample:
private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";
public static String Base36Encode(long input, char paddingChar, int totalWidth)
{
char[] clistarr = CharList.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 36]);
input /= 36;
}
return new string(result.ToArray()).PadLeft(totalWidth, paddingChar).ToUpper();
}
and then use it this way:
for(int i = 0; i < 1000; i++)
{
Debug.WriteLine(Base36Encode(i, '0', 6));
}
which will produce this:
000000, 000001, 000002, 000003, 000004, 000005, 000006, 000007, 000008, 000009, 00000A, 00000B, 00000C, 00000D, 00000E, 00000F, 00000G, 00000H, 00000I, 00000J, 00000K, 00000L, 00000M, 00000N, 00000O, 00000P, 00000Q, 00000R, 00000S, 00000T, 00000U, 00000V, 00000W, 00000X, 00000Y, 00000Z, 000010, 000011, 000012, 000013, 000014, 000015, 000016, 000017, 000018, 000019, 00001A, 00001B, 00001C, 00001D, 00001E, 00001F, 00001G, 00001H, 00001I, 00001J, 00001K, 00001L, 00001M, 00001N, 00001O, 00001P, 00001Q, 00001R, 00001S, 00001T, 00001U, 00001V, 00001W, 00001X, 00001Y, 00001Z, 000020, 000021, 000022, 000023, 000024, 000025, 000026, 000027, 000028, 000029, 00002A, 00002B, 00002C, 00002D, 00002E, 00002F, 00002G, 00002H, 00002I, 00002J, 00002K, 00002L, 00002M, 00002N, 00002O, 00002P, 00002Q, 00002R, 00002S, 00002T...
and the positive thing about this approach is that you can convert this back to number by using:
public static Int64 Base36Decode(string input)
{
var reversed = input.ToLower().Reverse();
long result = 0;
int pos = 0;
foreach (char c in reversed)
{
result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
pos++;
}
return result;
}

How to trim and convert a string to integer?

how could I trim and convert a string as following:
string abc = "15k34"
int x = first two characters of abc // should be 15
but if abc begins with "0"
for example - string abc = "05k34"
int x = first two characters of abc // should be 5
Try with following code:
string str = "15k34";
int val;
if (str.Length>1)
{
if (int.TryParse(str.Substring(0, 2), out val))
{
//val contains the integer value
}
}
string abc = "15k34";
int x = 0;
//abc = "05k34";
int val;
if (!string.IsNullOrEmpty(abc) && abc.Length > 1)
{
bool isNum = int.TryParse(str.Substring(0, 2), out val);
if (isNum)
{
x = val;
}
}
I think from the pseudocode you will typically have numbers with 'k' in them representing thousands.
So...
string abc = "15k34";
string[] numbers = abc.Split('k'); //This will return a array { "15", "34" }
int myInt = Convert.ToInt32(numbers[0]);
If the string was "05k34" the value of myInt would be 5 then.
documentation:
http://msdn.microsoft.com/en-us/library/1bwe3zdy
http://msdn.microsoft.com/en-us/library/bb397679.aspx

How can I delete the first n lines in a string in C#?

How can I delete the first n lines in a string?
Example:
String str = #"a
b
c
d
e";
String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
You can use LINQ:
String str = #"a
b
c
d
e";
int n = 2;
string[] lines = str
.Split(Environment.NewLine.ToCharArray())
.Skip(n)
.ToArray();
string output = string.Join(Environment.NewLine, lines);
// Output is
// "c
// d
// e"
If you need to take into account "\r\n" and "\r" and "\n" it's better to use the following regex:
public static class StringExtensions
{
public static string RemoveFirstLines(string text, int linesCount)
{
var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount);
return string.Join(Environment.NewLine, lines.ToArray());
}
}
Here are some more details about splitting text into lines.
Combination of Get the index of the nth occurrence of a string? (search for Environment.NewLine) and substring should do the trick.
Try the following:
public static string DeleteLines(string s, int linesToRemove)
{
return s.Split(Environment.NewLine.ToCharArray(),
linesToRemove + 1
).Skip(linesToRemove)
.FirstOrDefault();
}
the next example:
string str = #"a
b
c
d
e";
string output = DeleteLines(str, 2);
returns
c
d
e
Try this:
public static string DeleteLines (string text, int lineCount) {
while (text.Split('\n').Length > lineCount)
text = text.Remove(0, text.Split('\n')[0].Length + 1);
return text;
}
It might not be very efficient but it works perfectly for the little project i've been working on recently
Try the following:
private static string DeleteLines(string input, int lines)
{
var result = input;
for(var i = 0; i < lines; i++)
{
var idx = result.IndexOf('\n');
if (idx < 0)
{
// do what you want when there are less than the required lines
return string.Empty;
}
result = result.Substring(idx+1);
}
return result;
}
Note: This method is not ideal for extremely long multi-line strings as it does not consider memory management. If dealing with these kind of strings, I suggest you alter the method to use the StringBuilder class.
With ability to delete first n lines or last n lines:
public static string DeleteLines(
string stringToRemoveLinesFrom,
int numberOfLinesToRemove,
bool startFromBottom = false) {
string toReturn = "";
string[] allLines = stringToRemoveLinesFrom.Split(
separator: Environment.NewLine.ToCharArray(),
options: StringSplitOptions.RemoveEmptyEntries);
if (startFromBottom)
toReturn = String.Join(Environment.NewLine, allLines.Take(allLines.Length - numberOfLinesToRemove));
else
toReturn = String.Join(Environment.NewLine, allLines.Skip(numberOfLinesToRemove));
return toReturn;
}
public static string DeleteLines(string input, int linesToSkip)
{
int startIndex = 0;
for (int i = 0; i < linesToSkip; ++i)
startIndex = input.IndexOf('\n', startIndex) + 1;
return input.Substring(startIndex);
}

Categories