My front-end application sends strings that look like this:
"12-15"
to a back-end C# application.
Can someone give me some pointers as to how I could extract the two numbers into two variables. Note the format is always the same with two numbers and a hyphen between them.
string stringToSplit = "12-15";
string[] splitStringArray;
splitStringArray = stringToSplit.Split('-');
splitStringArray[0] will be 12
splitStringArray[1] will be 15
Split the string into parts:
string s = "12-15";
string[] num = s.Split('-');
int part1 = Convert.ToInt32(num[0]);
int part2 = Convert.ToInt32(num[1]);
int[] numbers = "12-15".Split('-')
.Select(x => {
int n;
int.TryParse(x, out n);
return n;
})
.ToArray();
We call Split on a string instance. This program splits on a single character
string s ="12-15";
string[] words = s.Split('-');
foreach (string word in words)
{
int convertedvalue = Convert.ToInt32(word );
Console.WriteLine(word);
}
string[] ss= s.Split('-');
int x = Convert.ToInt32(ss[0]);
int y = Convert.ToInt32(ss[1]);
more info
You can use the below code to split and it will return string for each value, then you can typecast it to any type you wish to ...
string myString = "12-15-18-20-25-60";
string[] splittedStrings = myString.Split('-');
foreach (var splittedString in splittedStrings)
{
Console.WriteLine(splittedString + "\n");
}
Console.ReadLine();
Here is the correct version without the wrong code
string textReceived = "12-15";
string[] numbers = textReceived.Split('-');
List<int> numberCollection = new List<int>();
foreach (var item in numbers)
{
numberCollection.Add(Convert.ToInt32(item));
}
String numberString = "12-15" ;
string[] arr = numberString.Split("-");
Now you will get a string array , you can use parsing to get the numbers alone
int firstNumber = Convert.ToInt32(arr[0]);
Helpful answer related to parsing :
https://stackoverflow.com/a/199484/5395773
You could convert that string explicitly to an integer array using Array.ConvertAll method and access the numbers using their index, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = Array.ConvertAll(number.Split('-'), int.Parse);
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[1]);
}
}
}
Or you can explicitly convert the numeric string using int.Parse method, the int keyword is an alias name for System.Int32 and it is preffered over the complete system type name System.Int32, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = number.Split('-');
var one = int.Parse(numbers[0]);
var two = int.Parse(numbers[1]);
Console.WriteLine(one);
Console.WriteLine(two);
}
}
}
Additional read: Please check int.Parse vs. Convert.Int32 vs. int.TryParse for more insight on parsing the input to integer
string str = null;
string[] strArr = null;
int count = 0;
str = "12-15";
char[] splitchar = { '-' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
MessageBox.Show(strArr[count]);
}
Related
I am trying to compare two string in C# and get the differences between them i.e words which are not present in the other string ignoring cases and commas just focusing on the words. If one string contains two or multiple the and the second string has one the, it means this will be disregarded as it exists in both. Example I have two strings like below;
Cat meet's a dog
Cat meet's a dog and a bird
The difference between those two strings is and bird because it does not exist in the first one or vise versa and I want to get those two words and bird either in a List or a new string with spaces between them and in other words I want the words which are not present in the other string. Is there a way this can be done in C#?
Here's a way using LINQ. You don't need the "ToList()" part, but you mentioned that as one form of output you'd want:
string str1 = "Cat meet's a dog";
string str2 = "Cat meet's a dog and a bird";
string[] str1Words = str1.ToLower().Split(' ');
string[] str2Words = str2.ToLower().Split(' ');
var uniqueWords = str2Words.Except(str1Words).Concat(str1Words.Except(str2Words)).ToList();
// Do whatever you want with uniqueWords instead
Console.WriteLine($"output: {String.Join(" ", uniqueWords)}");
#ngdeveloper. This is my variant of your solution (had to post it in a separate answer because of the length):
private static StringsDiff Difference(string firststring, string secondstring)
{
StringsDiff _stringsDiff = new StringsDiff();
char[] _firstStringArray = firststring.ToCharArray();
char[] _secondStringArray = secondstring.ToCharArray();
int shortestLenght;
int longestLenght;
bool firstIsLongest;
if (_firstStringArray.Length > _secondStringArray.Length)
{
firstIsLongest = true;
shortestLenght = _secondStringArray.Length;
longestLenght = _firstStringArray.Length;
}
else
{
firstIsLongest = false;
shortestLenght = _firstStringArray.Length;
longestLenght = _secondStringArray.Length;
}
for (int i = 0; i < shortestLenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = shortestLenght; i < longestLenght; i++)
{
if (firstIsLongest)
_stringsDiff._diffList1.Add(_firstStringArray[i]);
else
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
return _stringsDiff;
}
I wrote you a simple solution, hope it will help -
The main method is called 'Difference' it receive 2 strings to compare and return an object called StringDiff.
It runs 2 loops, first comparing between the two strings char by char and then adding the rest of the longer string.
The 'StringDiff' object is a class with 2 char lists that represnt the differences of each string.
In the main method i use String.join to convert the char lists to a string and print it.
internal class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("enter first string");
string firstString = Console.ReadLine();
Console.WriteLine("enter second string");
string secondString = Console.ReadLine();
StringsDiff _stringsDiff = Difference(firstString, secondString);
Console.WriteLine(
$"fist string difference: {string.Join("", _stringsDiff._diffList1)} / second string difference: {string.Join("", _stringsDiff._diffList2)}");
Console.WriteLine("/////////////////////////////////////");
}
}
private static StringsDiff Difference(string firststring, string secondstring)
{
StringsDiff _stringsDiff = new StringsDiff();
char[] _firstStringArray = firststring.ToCharArray();
char[] _secondStringArray = secondstring.ToCharArray();
int lenght;
if (_firstStringArray.Length > _secondStringArray.Length)
{
lenght = _secondStringArray.Length;
for (int i = 0; i < lenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = _secondStringArray.Length; i < _firstStringArray.Length; i++)
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
}
}
else
{
lenght = _firstStringArray.Length;
for (int i = 0; i < lenght; i++)
{
if (!_firstStringArray[i].Equals(_secondStringArray[i]))
{
_stringsDiff._diffList1.Add(_firstStringArray[i]);
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
for (int i = _firstStringArray.Length; i < _secondStringArray.Length; i++)
{
_stringsDiff._diffList2.Add(_secondStringArray[i]);
}
}
return _stringsDiff;
}
class StringsDiff
{
public List<char> _diffList1 = new List<char>();
public List<char> _diffList2 = new List<char>();
}
}
Remember to use "string.join" to connect the lists objects if you need a string.
Problem: I want to write a method that takes a message/index pair like this:
("Hello, I am *Name1, how are you doing *Name2?", 2)
The index refers to the asterisk delimited name in the message. So if the index is 1, it should refer to *Name1, if it's 2 it should refer to *Name2.
The method should return just the name with the asterisk (*Name2).
I have attempted to play around with substrings, taking the first delimited * and ending when we reach a character that isn't a letter, number, underscore or hyphen, but the logic just isn't setting in.
I know this is similar to a few problems on SO but I can't find anything this specific. Any help is appreciated.
This is what's left of my very vague attempt so far. Based on this thread:
public string GetIndexedNames(string message, int index)
{
int strStart = message.IndexOf("#") + "#".Length;
int strEnd = message.LastIndexOf(" ");
String result = message.Substring(strStart, strEnd - strStart);
}
If you want to do it the old school way, then something like:
public static void Main(string[] args)
{
string message = "Hello, I am *Name1, how are you doing *Name2?";
string name1 = GetIndexedNames(message, "*", 1);
string name2 = GetIndexedNames(message, "*", 2);
Console.WriteLine(message);
Console.WriteLine(name1);
Console.WriteLine(name2);
Console.ReadLine();
}
public static string GetIndexedNames(string message, string singleCharDelimiter, int index)
{
string valid = "abcdefghijlmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
string[] parts = message.Split(singleCharDelimiter.ToArray());
if (parts.Length >= index)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < parts[index].Length; i++)
{
string character = parts[index].Substring(i, 1);
if (valid.Contains(character))
{
sb.Append(character);
}
else
{
return sb.ToString();
}
}
return sb.ToString();
}
return "";
}
You can try using regular expressions to match the names. Assuming that name is a sequence of word characters (letters or digits):
using System.Linq;
using System.Text.RegularExpressions;
...
// Either name with asterisk *Name or null
// index is 1-based
private static ObtainName(string source, int index) => Regex
.Matches(source, #"\*\w+")
.Cast<Match>()
.Select(match => match.Value)
.Distinct() // in case the same name repeats several times
.ElementAtOrDefault(index - 1);
Demo:
string name = ObtainName(
"Hello, I am *Name1, how are you doing *Name2?", 2);
Console.Write(name);
Outcome:
*Name2
Perhaps not the most elegant solution, but if you want to use IndexOf, use a loop:
public static string GetIndexedNames(string message, int index, char marker='*')
{
int lastFound = 0;
for (int i = 0; i < index; i++) {
lastFound = message.IndexOf(marker, lastFound+1);
if (lastFound == -1) return null;
}
var space = message.IndexOf(' ', lastFound);
return space == -1 ? message.Substring(lastFound) : message.Substring(lastFound, space - lastFound);
}
Input:
string param = "1100,1110,0110,0001";
Output:
int[] matrix = new[]
{
1,1,0,0,
1,1,1,0,
0,1,1,0,
0,0,0,1
};
What I did?
First of all I splited string to string[].
string[] resultantArray = param.Split(',');
Created one method, where I passed my string[].
var intArray = toIntArray(resultantArray);
static private int[] toIntArray(string[] strArray)
{
int[] intArray = new int[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
intArray[i] = int.Parse(strArray[i]);
}
return intArray;
}
Issue?
I tried many solutions of SO, but none of them helped me.
Ended up with array without leading zeroes.
determine all digits: .Where(char.IsDigit)
convert the selected char-digits into integer: .Select(x => x-'0') (this is not as pretty as int.Parse or Convert.ToInt32 but it's super fast)
Code:
string param = "1100,1110,0110,0001";
int[] result = param.Where(char.IsDigit).Select(x => x-'0').ToArray();
As CodesInChaos commented, this could lead to an error if there are other type of Digits within your input like e.g. Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙' where char.IsDigit == true - if you need to handle such special cases you can allow only 0 and 1 in your result .Where("01".Contains)
You could also remove the commas and convert the result character-wise as follows using Linq.
string param = "1100,1110,0110,0001";
int[] result = param.Replace(",", "").Select(c => (int)Char.GetNumericValue(c)).ToArray();
yet another way to do this
static private IEnumerable<int> toIntArray(string[] strArray)
{
foreach (string str in strArray)
{
foreach (char c in str)
{
yield return (int)char.GetNumericValue(c);
}
}
}
What about this?
string input = "1100,1110,0110,0001";
var result = input
.Split(',')
.Select(e => e.ToCharArray()
.Select(f => int.Parse(f.ToString())).ToArray())
.ToArray();
string[] s=param.split(',');
Char[] c;
foreach(string i in s){
c+=i.ToCharArray()
}
int[] myintarray;
int j=0;
foreach(char i in c){
myintarray[j]=(int)i;
j++
}
I've been creating a code breaking software and I need to convert the characters from a text file into ascii numbers to allow the shift. I have left my code below but could someone explain how I could do this?
using System;
using System.IO;
namespace CipherDecoder
{
class Program
{
static void Main(string[] args)
{
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
string cipherText = File.ReadAllText(fileText);
string output = #"C:\\Users\Samuel\Documents\Computer_Science\PaDS\output.txt\";
char[] cipherChars = new char[691];
int j = 0;
foreach (char s in cipherText)
{
cipherChars[j] = s;
j++;
}
for(int i = 0; i < cipherChars.Length; i++)
{
cipherChars[i] = cipherChars[i];
}
}
}
}
To get the int values into an int array you could just do this with as a LINQ select. For example:
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
int [] charactersAsInts = File.ReadAllText(fileText).Select(chr => (int)chr).ToArray();
You can,
var asciiNumbersArray = cipherText.Cast<int>().ToArray();
If you cast a char to int you get the ascii number in decimal system.
So I have these two functions,
public static string[] CharToHex(string str, string prefix, string delimeter)
{
List<string> list = new List<string>();
foreach (char c in str)
{
list.Add(prefix + String.Format("{0:X2}",(int)c) + delimeter);
}
return list.ToArray();
}
public static string[] StrToChar(string str, string prefix, string delimeter)
{
List<string> list = new List<string>();
foreach (char c in str)
{
list.Add(prefix + (int)c + delimeter);
}
return list.ToArray();
}
Basically, I'm trying to show the Sum'd value of both returned arrays in a label.
I created a function to calculate a sum,
public static string ArraySum(int[] array)
{
string sum = array.Sum().ToString();
return sum;
}
And another function to take the string array and convert it to a string,
public static string StringArrayToString(string[] array)
{
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
builder.Append(value);
}
return builder.ToString();
}
This is how I'm putting it all together,
string[] dec = StrToChar(txtInput.Text, txtPrefix.Text, txtDelimiter.Text);
string[] hex = CharToHex(txtInput.Text, txtPrefix.Text, txtDelimiter.Text);
string decStr = StringArrayToString(dec);
string hexStr = StringArrayToString(hex);
int[] decCount = dec.Select(x => int.Parse(x)).ToArray();
int[] hexCount = hex.Select(x => int.Parse(x)).ToArray();
var builder = new StringBuilder();
Array.ForEach(decCount, x => builder.Append(x));
var res = builder.ToString();
txtDecimal.Text = decStr;
txtHex.Text = hexStr;
lblDecimalSum.Text = res;
The issue here is, this obviously isn't working, it also seems horribly inefficient, there has to be an easier way of doing all of this and also, my sum isn't properly summing up the array elements.
I'm not entirely sure how to go about doing this and any assistance / feedback would be greatly appreciated.
Thank you kindly.
If I understand you correctly, you're trying to get the add the value of each character of a string together, not parse an int from a string and add those together. If that's the case, you can do it with linq:
string x = "xasdgdfhdsfh";
int sum = x.Sum(b => b);
In fact using linq, you can accomplish everything you want to do:
string x = "xasdgdfhdsfh";
string delim = txtDelimiter.Text;
string prefix = txtPrefix.Text;
lblDecimalSum.Text = x.Sum(c => c).ToString();
txtDecimal.Text =
string.Join(delim, x.Select(c => prefix + ((int)c).ToString()));
txtHex.Text =
string.Join(delim, x.Select(c => prefix + ((int)c).ToString("X2")));