I have a string input like:
1 3 4 1 2
I want to Sum the number into integer. I tried the following code:
using System;
public class Program
{
public static void Main()
{
string input2 = "1 3 4 1 1";
string value2 = input2.Replace(" ", "+");
int val = int.Parse(value2);
Console.WriteLine(val);
}
}
But it is not correct. Does anyone have an idea for this?
Thank you.
You can try Split the initial string (input2) into items, TryParse them into corresponding int bvalues and then Sum them with a help of Linq:
using System.Linq;
...
int val = value2
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Sum(item => int.TryParse(item, out int value) ? value : 0);
Here all invalid items (i.e. items which can't be parsed as an integer) are ignored (we turn them into 0). You may want an exception thrown in this case:
using System.Linq;
...
int val = value2
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Sum(item => int.Parse(item));
Finally, your code amended (we can use an old trick with DataTable.Compute):
using System.Data;
...
string input2 = "1 3 4 1 1";
string formula = input2.Replace(' ', '+');
using (DataTable table = new DataTable())
{
int val = Convert.ToInt32(table.Compute(formula, null));
Console.WriteLine(val);
}
You can Split input2 with a space character into an array then use system.linq.enumerable.sum()
string input2 = "1 3 4 1 1";
var result= input2.Split(' ').Sum(x=> int.Parse(x));
Related
I'm trying to get a sum value based on what characters a string contains. The character values are determined by me and are somewhat arbitrary ('A' = 1, 'B' = 4, 'C' = 2, etc.). For example, if string s = "ABC" then int value = 7 because 1 + 4 + 2 = 7. What would be an efficient way to write this in C#?
Right now my code looks like this:
//Declare variables
string name = JOHN
int i = 0;
int nameValue = 0;
string temp = "";
string[] nameArray;
//Convert name to string array so I can use String.Contains() to check what letters are in name
foreach (char c in name)
{
temp += c.ToString();
temp += ".";
}
temp = temp.Remove(temp.Length - 1, 1);
nameArray = temp.Split('.');
//Determine nameValue by iterating through nameArray and checking each string
foreach (string s in nameArray)
{
if (nameArray[i].Contains('A')) { nameValue += 1 }
else if (nameArray[i].Contains('B')) { nameValue += 4 }
else if (nameArray[i].Contains('C')) { nameValue += 2 }
else if (nameArray[i].Contains('D')) { nameValue += 3 }
.
.
.
else if (nameArray[i].Contains('Y')) { nameValue += 7 }
else if (nameArray[i].Contains('Z')) { nameValue += 5 }
i++;
}
Console.WriteLine(nameValue);
I changed the string to a string array because I have names that have repeating letters (i.e. Jill), and I want to give every letter in the name a value. If I used String.Contains() without separating every letter, it would only count repeating letters once, I think.
I feel like there has to be a better way than doing all that string manipulation and using a separate conditional statement for every letter in the alphabet, but I couldn't find anything. Thanks.
If you want to map consequent characters (say, 'A'..'Z') to integer values, I suggest using array:
using System.Linq;
...
int[] map = new int[] {
//TODO: put corresponding integer values starting from 'A'
4, 2, 3
};
...
s = "ABC";
int sum = s.Sum(c => map[c - 'A']);
In general case, if you want to map arbitrary symbols, you can use dictionary:
using System.Linq;
...
Dictionary<char, int> map = new Dictionary<char, int>() {
//TODO: put all required pairs here
{'A', 4},
{'B', 2},
{'C', 1},
{'#', -123},
};
...
s = "ABC";
// if there's no map (e.g. for '*'), we assume the value being 0
int sum = s.Sum(c => map.TryGetValue(c, out int v) ? v : 0);
http://www.asciitable.com/
you will see that capitol A is 65
string str = "Hi there";
foreach(char c in str.ToUpper())
{
value += ((int)c) - 64;
}
I have this file called failas.txt. It contains text in Lithuanian language. I did Encoding 1257 for it so it can read Lithuanian letters.
Now all I have to do is to make an array for each Lithuanian letter used in that file.
All those letters are in string p = "AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ";
Array should show how many times each letter is repeated in a text and write those results to a new txt file called rezultatai.txt. So the code is this:
using System;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Collections;
using System.IO; skirta biblioteka
using System.Text;
using System.Threading;
class Program
{
static void Main()
{
string failas = "failas.txt";
string rodymas = File.ReadAllText(failas, Encoding.GetEncoding(1257));
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(rodymas);
char[] masyvas = rodymas.Where(Char.IsLetter).OrderBy(Char.ToLower).ToArray();
foreach (char c in masyvas)
{
Console.Write(c + ",");
}
string p = "AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ";
failas = failas.ToUpper();
Dictionary<char, int> dict = new Dictionary<char, int>();
foreach (char c in p) dict.Add(c, 0);
foreach (char c in failas)
{
int val;
if (dict.TryGetValue(c, out val)) dict[c] = val + 1;
}
//write to a file..
foreach (KeyValuePair<char, int> item in dict)
{
if (item.Value > 0) Console.WriteLine("Character {0}, No of Occurences = {1}", item.Key, item.Value);
File.AppendAllText("rezultatai.txt", item.Value + Environment.NewLine);
}
Console.WriteLine("Sum = {0}", dict.Sum(x => x.Value));
Console.ReadKey();
However, somehow it returns only output with letters A, F, I, L, S, T. Like this:
Character A, No of Occurences = 2
Character F, No of Occurences = 1
Character I, No of Occurences = 1
Character L, No of Occurences = 1
Character S, No of Occurences = 1
Character T, No of Occurences = 2
As I mentioned before, letters should be:
AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ
Also, when I open rezultatai.txt file to check appended values, it only contains a long column of numbers:
2
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
1
0
0
0
0
0
1
0
2
0
0
0
0
0
0
2
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
1
0
0
0
0
0
1
0
2
0
However, somehow it returns only output with letters A, F, I, L, S, T. Like this:
foreach (char c in failas)
You iterate over the filename, which is "failas.txt", This should be the actual file's text.
foreach (char c in rodymas)
foreach (char c in masyvas) // Possibly the char array.. not sure which..
Also, when I open rezultatai.txt file to check appended values, it only contains a long column of numbers:
Yes, you append the value from a KeyValuePair where the value is an integer, this presumably needs to be the same as what you output to the console.
.NET has pretty powerful features, like LINQ and the CultureInfo system. You can use both to do this in a few lines:
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
internal class Program
{
private static void Main()
{
var cultureLithunia = new CultureInfo("lt-LT");
var textInfoLithunia = cultureLithunia.TextInfo;
string requested = textInfoLithunia.ToUpper("AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ");
string content = File.ReadAllText("failas.txt", Encoding.GetEncoding(textInfoLithunia.ANSICodePage));
var characters = content.GroupBy(c => c);
var charactersYouWant = characters.Where(c => requested.Contains(textInfoLithunia.ToUpper(c.Key)));
var linesYouWantToOutput = charactersYouWant.Select(c => string.Format("Character {0}, No of Occurences = {1}", c.Key, c.Count()));
File.WriteAllLines("rezultatai.txt", linesYouWantToOutput);
Console.WriteLine("Done");
Console.ReadKey();
}
}
If you want all characters from the required text, it's a bit more complicated:
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
internal class Program
{
private static void Main()
{
var cultureLithunia = new CultureInfo("lt-LT");
var textInfoLithunia = cultureLithunia.TextInfo;
string requested = textInfoLithunia.ToUpper("AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ");
string content = File.ReadAllText("failas.txt", Encoding.GetEncoding(textInfoLithunia.ANSICodePage));
var characters = content.GroupBy(c => c);
var charactersYouWant = requested.Select(c => new { Key = c, Count = characters.Where(cc => textInfoLithunia.ToUpper(cc.Key) == c).Select(group => group.Count()).FirstOrDefault() });
var linesYouWantToOutput = charactersYouWant.Select(c => string.Format("Character {0}, No of Occurences = {1}", c.Key, c.Count));
File.WriteAllLines("rezultatai.txt", linesYouWantToOutput);
Console.WriteLine("Done");
Console.ReadKey();
}
}
I have a text file containing the following content:
0 0 1 0 3
0 0 1 1 3
0 0 1 2 3
0 0 3 0 1
0 0 0 1 2 1 1
0 0 1 0 3
0 0 1 1 3
0 0 1 2 3
0 0 3 0 1
0 0 1 2 3
0 0 3 0 1
There are no spaces between the rows but there is a space between the numbers. I want to read these integers from a txt file and save in a list of int arrays in C#.
Let's say your string is called text, and contains "1 1 1 0 3 2 3" etc.
You declare a string array.
String[] numbers1=text.Split(" ");
Now declare your int array and convert each one to int.
int[] numbers2=new int[numbers.Length];
for(int i=0; i<numbers.Length; i++)
numbers2[i]=Convert.ToInt32(numbers1[i]);
And you're done.
This works for me:
var numbers =
System.IO.File
.ReadAllLines(#"C:\text.txt")
.Select(x => x.Split(' ')
.Select(y => int.Parse(y))
.ToArray())
.ToList();
I get this result:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileToIntList
{
class Program
{
static void Main(string[] args)
{
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("C:\\Users\\M.M.S.I\\Desktop\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
//Console.WriteLine(myString);
char rc = (char)10;
String[] listLines = myString.Split(rc);
List<List<int>> listArrays = new List<List<int>>();
for (int i = 0; i < listLines.Length; i++)
{
List<int> array = new List<int>();
String[] listInts = listLines[i].Split(' ');
for(int j=0;j<listInts.Length;j++)
{
if (listInts[j] != "\r")
{
array.Add(Convert.ToInt32(listInts[j]));
}
}
listArrays.Add(array);
}
foreach(List<int> array in listArrays){
foreach (int i in array)
{
Console.Write(i + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
var resultList = new List<int>();
File.ReadAllLines("filepath")
.ToList()
.ForEach((line) => {
var numbers = line.Split()
.Select(c => Convert.ToInt32(c));
resultList.AddRange(numbers);
});
using System.IO;
using System.Linq;
string filePath = #"D:\Path\To\The\File.txt";
List<int[]> listOfArrays =
File.ReadLines(path)
.Select(line => line.Split(' ').Select(s => int.Parse(s)).ToArray())
.ToList();
Since you mention that it is your first time programming in C#, this version may be easier to understand; the process is the same as the above:
using System.IO;
using System.Linq;
string filePath = #"D:\Path\To\The\File.txt";
IEnumerable<string> linesFromFile = File.ReadLines(path);
Func<string, int[]> convertStringToIntArray =
line => {
var stringArray = line.Split(' ');
var intSequence = stringArray.Select(s => int.Parse(s)); // or ....Select(Convert.ToInt32);
var intArray = intSequance.ToArray();
return intArray;
};
IEnumerable<int[]> sequenceOfIntArrays = linesFromFile.Select(convertStringToIntArray);
List<int[]> listOfInfArrays = sequenceOfIntArrays.ToList();
I have a question about split string and put it in DataTable. How can i know if the second array is a string or number?
I have a text with many string like this:
text : ...
abc 123 def 1 \"ok lo\" ;
abc def 1 \"ok lo\" ;
...
array2:
tmpList[0] = abc
tmpList[1] = 123
tmpList[2] = def
tmpList[3] = 1 \"ok lo\"
array1:
tmpList[0] = abc
tmpList[1] = def
tmpList[2] = 1 \"ok lo\
To find all strings startwith abc i did:
StreamReader fin = new StreamReader(userSelectedFilePath1);
string tmp = "";
while ((tmp = fin.ReadLine()) != null)
{
if (tmp.StartsWith("abc "))
{
var tmpList1 = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
{
if (i % 2 == 1) return new[] { s };
return s.Split(new[] { ' ', ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
}).ToList();
table.Rows.Add(new object[] { tmpList1[0], tmpList1[1], tmpList1[2], tmpList1[3]});
}
}
With this code i can find String startswith abc, split and put in DataTable. How can i know if the second index is a string or int? Becasuse with what i did i have a error with second index and it splits not correcly. I think about if(tmp.StartsWith(abc NUMBER?)) else do the code above
When you do String.Split(), all of the values in the array will be Strings as well, so in your example for ABC:
tmpList[1] = 123 // this is incorrect as the value is an int
This should be:
tmpList[1] = "123" // value is a string
Then what you can do is try to cast the value to an int, and if it fails, you know it's not an int:
int number;
bool result = Int32.TryParse(tmpList[1], out number);
if (result) {
// your code for if the value is a number
}
else {
// your code for if the value is not a number
}
Code example copied from here.
I have got column in db which saves the string as 1,2,3,4,5
I want to separate the string to 1 2 3 4 5 and save each number in the array , for instance the array should be like int [] numbers , int[0] = 1 , int[1] = 2 ......
Looks like you want:
int[] array = text.Split(',')
.Select(x => int.Parse(x, CultureInfo.InvariantCulture))
.ToArray();
Obviously this will go bang if any of the split results is not a parsable integer.
(You may also want to use a List<int> instead of an array, as a generally more flexible collection type.)
EDIT: Short but complete demo program:
using System;
using System.Globalization;
using System.Linq;
public class Test
{
static void Main()
{
string eventIds = "1,2,3";
int[] array =
eventIds.Split(',')
.Select(x => int.Parse(x, CultureInfo.InvariantCulture))
.ToArray();
foreach (int id in array)
{
Console.WriteLine(id);
}
}
}
here is code
Dim str as String = "1,2,3,4,5"
dim objstr() as String = str.split(",")
here split return array.
Here's a "safer" version of John's excellent code snippet that will deal with values that cannot be parsed as int by adding them as 0:
int temp;
int[] array = text.Split(',')
.Select(x => int.TryParse(x, out temp) ? temp : 0)
.ToArray();
If you want to be totally safe and discard any values that cannot be converted to an integer then you could use a function like this:
private static int[] ConvertTextToIntArray(string text)
{
var integerList = new List<int>();
var values = text.Split(',');
int temp;
foreach (var value in values)
{
if (int.TryParse(value, out temp))
{
integerList.Add(temp);
}
}
return integerList.ToArray();
}