C# Set variable from numbers on either side of a comma? - c#

I have a textbox where the user would enter a set of numbers seperated by commas, ("1, 2, 3 , 4"). I need to set a variable for each one of these numbers. Is this possible?

why not store it in an array?
string val = textbox.text;
string[] arr = val.Split(',');
example
using System;
class Program
{
static void Main()
{
string s = "1,2,3,4";
string[] numbers = s.Split(',');
foreach (string num in numbers)
{
Console.WriteLine(num);
}
}
}
Output
1
2
3
4

Take the value of the textbox and split it on comma. You would then have a string array of the values that should be adequate for further use.
http://www.dotnetperls.com/split

Related

Splitting string value c#

I want to know about how to splitting a value in string format in to two parts. Here in my asp application I'm parsing string value from view to controller.
And then I want to split the whole value in to two parts.
Example like: Most of the times value firest two letters could be TEXT value (like "PO" , "SS" , "GS" ) and the rest of the others are numbers (SS235452).
The length of the numbers cannot declare, since it generates randomly. So Want to split it from the begining of the string value. Need a help for that.
My current code is
string approvalnumber = approvalCheck.ApprovalNumber.ToUpper();
Thanks.
As you already mentioned that first part will have 2 letters and it's only second part which is varying, you can use Substring Method of String as shown below.
var textPart = input.Substring(0,2);
var numPart = input.Substring(2);
The first line fetches 2 characters from starting index zero and the second statement fetches all characters from index 2. You can cast the second part to a number if required.
Please note that the second parameter of Substring is not mentioned in second line. This parameter is for length and if nothing is mentioned it fetches till end of string.
You could try using regex to extract alpha, numbers from the string.
This javascript function returns only numbers from the input string.
function getNumbers(input) {
return input.match(/[0-9]+/g);
}
I'd use a RegExp. Considering the fact that you indicate ASP-NET-4 I assume you can't use tuples, out var etc. so it'd go as follows:
using System.Text.RegularExpressions;
using FluentAssertions;
using Xunit;
namespace Playground
{
public class Playground
{
public struct ProjectCodeMatch
{
public string Code { get; set; }
public int? Number { get; set; }
}
[Theory]
[InlineData("ABCDEFG123", "ABCDEFG", 123)]
[InlineData("123456", "", 123456)]
[InlineData("ABCDEFG", "ABCDEFG", null)]
[InlineData("ab123", "AB", 123)]
public void Split_Works(string input, string expectedCode, int? expectedNumber)
{
ProjectCodeMatch result;
var didParse = TryParse(input, out result);
didParse.Should().BeTrue();
result.Code.Should().Be(expectedCode);
result.Number.Should().Be(expectedNumber);
}
private static bool TryParse(string input, out ProjectCodeMatch result)
{
/*
* A word on this RegExp:
* ^ - the match must happen at the beginning of the string (nothing before that)
* (?<Code>[a-zA-Z]+) - grab any number of letters and name this part the "Code" group
* (?<Number>\d+) - grab any number of numbers and name this part the Number group
* {0,1} this group must occur at most 1 time
* $ - the match must end at the end of the string (nothing after that)
*/
var regex = new Regex(#"^(?<Code>[a-zA-Z]+){0,1}(?<Number>\d+){0,1}$");
var match = regex.Match(input);
if (!match.Success)
{
result = default;
return false;
}
int number;
var isNumber = int.TryParse(match.Groups["Number"].Value, out number);
result = new ProjectCodeMatch
{
Code = match.Groups["Code"].Value.ToUpper(),
Number = isNumber ? number : null
};
return true;
}
}
}
A linq answer:
string d = "PO1232131";
string.Join("",d.TakeWhile(a => Char.IsLetter(a)))

I am trying to extract only numbers from a text file in c#

I am trying to extract only numbers from a text file in c#. My text file is like as below
xasd 50 ysd 20 zaf 40 bhar 60
I am trying to browse a file with openfileDialoug and read that file and extract the numbers from the same file and need to compare those values with a constant value say 60. I need to display how many numbers are present more than that constant number. If those numbers are greater than 60 then i need to append the number of greater values to richtextBox along with the existing text.
You can use the Int32.TryParse(string s,out int result) method. It returns true if the string s can be parsed as an integer and stores the value in int result. Also, you can use the String.Split(Char[]) method to split the line you read from Text File.
string line = fileObject.ReadLine();
int constant = 60; //For your example
int num = 0;
string []tokens = line.Split(); //No arguments in this method means space is used as the delimeter
foreach(string s in tokens)
{
if(Int32.TryParse(s, out num)
{
if(num > constant)
{
//Logic to append to Rich Text Box
}
}
}
Regex is an elegant way to find numbers in a string which is the OP requirement, something like:
string allDetails = File.ReadAllText(Path);
result = Regex.Match(allDetails, #"\d+").Value;
Now the resultString will contain all the extracted integers
In case you want to take care of negative numbers too=, then do this modification
result = Regex.Match(allDetails, #"-?\d+").Value;
Hope this helps, check out the following post:
Find and extract a number from a string
If your file is always like as you have shown then you can easily split it and parse:
string filePath = ""; // from OpenFileDialog
string fileContents = File.ReadAllText(filePath);
string[] values = fileContents.Split();
int valueInt, greaterValuesCount = 0;
foreach (var value in values)
{
if (int.TryParse(value, out valueInt))
{
greaterValueCount++;
// Do something else here
}
}

Extract multiple integers from string and store as int

I know that this will extract the number and store as int -
string inputData = "sometex10";
string data = System.Text.RegularExpressions.Regex.Match(inputData, #"\d+").Value;
int number1 = Convert.ToInt32(data);
I am trying to extract multiple numbers from a string eg- 10 + 2 + 3 and store these as separate integers.
note : the amount of numbers the user will type in is unknow.
Any suggestions much appreciated thanks
You can use a LINQ one-liner:
var numbers = Regex.Matches(inputData, #"\d+").Select(m => int.Parse(m.Value)).ToList();
Or use ToArray() if you prefer an array instead of a list.
C# program that uses Regex.Split
Referencing : http://www.dotnetperls.com/regex-split
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
//
// String containing numbers.
//
string sentence = "10 cats, 20 dogs, 40 fish and 1 programmer.";
//
// Get all digit sequence as strings.
//
string[] digits = Regex.Split(sentence, #"\D+");
//
// Now we have each number string.
//
foreach (string value in digits)
{
//
// Parse the value to get the number.
//
int number;
if (int.TryParse(value, out number))
{
Console.WriteLine(number);
}
}
}
}
You can use something like this:
string inputData = "sometex10";
List<int> numbers = new List<int>();
foreach(Match m in Regex.Matches(inputData, #"\d+"))
{
numbers.Add(Convert.ToInt32(m.Value));
}
This will store the integers in the list numbers

How to read Two numbers in c# [duplicate]

This question already has answers here:
reading two integers in one line using C#
(12 answers)
Closed 8 years ago.
INPUT
67 89 (in single line)
I have to input two numbers from console , and store in two different integers variable .
HOw to do it.
This will read a line from the console, split the string, parse the integers, and output a list. You can then take each number from the list as needed.
Console.ReadLine().Split().Select(s => int.Parse(s)).ToList()
If there will always be two numbers you can do it as follows:
var integers = Console.ReadLine().Split().Select(s => int.Parse(s)).ToArray();
int first = integers[0];
int second = integers[1];
Areas for improvement:
You might want to use TryParse instead of Parse and output a friendly error message if the input does not parse
If you require exactly 2 numbers (no more, no less) you might want to check the length of integers and output a friendly error message if <> 2
TryParse() example as requested:
var numbers = new List<int>();
foreach (string s in Console.ReadLine().Split())
{
if (int.TryParse(s, out int number))
numbers.Add(number);
else
Console.WriteLine($"{s} is not an integer");
}
using System;
public class Program
{
static void Main(string[] args)
{
var numbers = Console.ReadLine();
var numberList = numbers.Split(' ');
var number1 = Convert.ToInt32(numberList[0]);
var number2 = Convert.ToInt32(numberList[1]);
Console.WriteLine(number1 + number2);
Console.ReadKey();
}
}
If you executing from other program the you need to read from the args
var result = Console.ReadLine().Split(new [] { ' '});
Something along those lines, top of my head.
See the documentation for Console.ReadLine() and String.Split()
Using Linq you can then project into an int array:
var result = Console.ReadLine()
.Split(new[] { ' ' }) //Explicit separator char(s)
.Select(i => int.Parse(i))
.ToArray();
And even a bit terser:
var result = Console.ReadLine()
.Split() //Assuming whitespace as separator
.Select(i => int.Parse(i))
.ToArray();
Result is now an array of ints.

How can I parse an integer and the remaining string from my string?

I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"

Categories