Extract string parts that are separated with commas - c#

I need to extract a string into 3 different variables.
The input from the user will be in this format 13,G,true.
I want to store the number in an integer, the "G" in a character and "true" into a string.
But I don't know how to specify the comma location so the characters before or after the comma can be stored in another variable.
I'm not allowed to use the LastIndexOf method.

string msg = "13,G,true";
var myArray = msg.Split(",");
// parse the elements
int number;
if (!Int32.TryParse(myArray[0], out number) throw new ArgumentException("Whrong input format for number");
string letter = myArray[1];
string b = myArry[2];
// or also with a boolean instead
bool b;
if (!Int32.TryParse(myArray[2], out b) throw new ArgumentException("Whrong input format for boolean");

use String.Split
string str='13,G,true';
string[] strArr=str.Split(',');
int32 n=0,intres=0;
char[] charres = new char[1];
string strres="";
if(!Int32.TryParse(strArr[0], out n))
{
intres=n;
}
if(strArr[0].length>0)
{
charres[0]=(strArr[1].toString())[0];
}
strres=strArr[2];
//you'll get 13 in strArr[0]
//you'll get Gin strArr[1]
//you'll get true in strArr[2]

var tokens = str.Split(","); //Splits to string[] by comma
var first = int32.Parse(tokens[0]); //Converts first string to int
var second = tokens[1][0]; //Gets first char of the second string
var third = tokens[2];
But be aware, that you also need to validate the input

You are going to need method String.Split('char'). This method splits string using specified char.
string str = "13,G,true";
var arrayOfStrings=str.Split(',');
int number = int.Parse(arrayOfStrings[0]);

// original input
string line = "13,G,true";
// splitting the string based on a character. this gives us
// ["13", "G", "true"]
string[] split = line.Split(',');
// now we parse them based on their type
int a = int.Parse(split[0]);
char b = split[1][0];
string c = split[2];
If what you are parsing is CSV data, I would check out CSV parsing libraries related to your language. For C#, Nuget.org has a few good ones.

Related

Why do i get this error, 'Input string was not in a correct format.'

I am trying to get an input of #1-1-1 and I need to take the numbers from this string and put them into a list of type int. I have tried to do this using this code:
List<int>numbers = new List<int>();
numbers = Console.ReadLine().Split('-', '#').ToList().ConvertAll<int>(Convert.ToInt32);
Shouldn't the input get split into an array of the numbers I want, then get turned into a list, then get converted into a int list?
Your problem is not the .split('-','#'). This splits the string into a string[] with four entrys (in this example). The first one is an empty string. This cannot be convertet into a Int32.
As a hotfix:
var numbers = Console.ReadLine().Split('-', '#').ToList();
//numbers.RemoveAt(0); <- this is also working
numbers.Remove(string.Empty);
var ret = numbers.ConvertAll<int>(Convert.ToInt32);
That will work for your "#1-1-1 " case. But you should check for non integer chars in the list before converting.
string input = " #1-1-1";
var numbers = Console.ReadLine().Replace("#", "").Split('-').Select(int.Parse).ToList();
You can do it this way
List<int> numbers = new List<int>();
string[] separators = new string[] { "-", "#" };
numbers = Console.ReadLine().Split(separators,StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll<int>(Convert.ToInt32);

String with index conversion or array of numbers

Why i can't convert this string to a number? Or how to make a array of numbers from this string.
string str = "110101010";
int c = Int32.Parse(str[0]);
str is a string so str[0] returns a char and the Parse method doesnt take a char as input but rather a string.
if you want to convert the string into an int then you would need to do:
int c = Int32.Parse(str); // or Int32.Parse(str[0].ToString()); for a single digit
or you're probably looking for a way to convert all the individual numbers into an array which can be done as:
var result = str.Select(x => int.Parse(x.ToString()))
.ToArray();
I assume you are trying to convert a binary string into its decimal representation.
For this you could make use of System.Convert:
int c = Convert.ToInt32(str, 2);
For the case that you want to sum up all the 1s and 0s from the string you could make use of System.Linq's Select() and Sum():
int c = str.Select(i => int.Parse(i.ToString())).Sum();
Alternatively if you just want to have an array of 1s and 0s from the string you could omit the Sum() and instead enumerate to an array using ToArray():
int[] c = str.Select(i => int.Parse(i.ToString())).ToArray();
Disclaimer: The two snippets above using int.Parse()would throw an exception if str were to contain a non-numeric character.
Int32.Parse accepts string argument, not char which str[0] returs.
To get the first number, try:
string str = "110101010";
int c = Int32.Parse(str.Substring(0, 1));

How can I add an integer to an existing record?

Please be kind enough to tell me how I can add an integer to an existing record which starts with a string sequence like the following;
S0000 - S00027
Kind Regards,
Indunil Sanjeewa
Try this code:
string record = "S00009";
string recordPrefix = "S";
char paddingCharacter = '0';
string recordNoPart = record.Substring(recordPrefix.Length);
int nextRecordNo = int.Parse(recordNoPart) + 1;
string nextRecord = string.Format("{0}{1}", recordPrefix, nextRecordNo.ToString().PadLeft(record.Length - recordPrefix.Length, paddingCharacter));
#kurakura88 has already given the logic. I have just provided the hardcore c# code.
The logic is:
separate the "S00009" into "S" and "00009". Use string method Substring()
Parse "00009" into integer. Use Int.Parse or Int.TryParse
Add 1 into the integer
Print back the "S" and the integer. Use string.Concat or simply string + integer
You can use following approach
string input = #"S0000";
string pattern = #"\d+";
string format = #"0000";
int addend = 1;
string result = Regex.Replace(input, pattern,
m => (int.Parse(m.Value) + addend).ToString(format));
// result = S0001
Regular expression \d+ matches all digits.
MatchEvaluator converts matched value to integer. Then adds the addend. Then converts the value to a string using the specified format.
In the end using the Replace method replaces the previous value with the new value.

How do I check the number of occurences of a certain string in another string?

string containsCharacter = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(containsCharacter).Length - 1;
I originally pulled this code off another person's question's answer but it doesn't seem to work with text boxes.
Errors I'm getting:
The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Argument 1: cannot convert from 'string' to 'char[]'
I prefer to fix this code rather than use other things like LINQ but I would accept it if there isn't a way to fix this code.
You could iterate through the characters
string value = "BANANA";
int x = 0;
foreach (char c in value)
{
if (c == 'A')
x++;
}
string containsCharacter = "t";
string testString = "test string contains certain characters";
int count = testString.Count(x => x.ToString() == containsCharacter);
This example will return 6.
The Split version you are using expects a character as input. This is the version for strings:
string containsText = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(new string[]{containsText}, StringSplitOptions.None).Length - 1;
With this code, count will be: 1 if textBox1.Text includes "test", 6 if it contains "t", etc. That is, it can deal with any string (whose length might be one, as a single character, or as big as required).
You can call ToCharArray on the string to make it a char[], like this:
int count = testString.Split(containsCharacter.ToCharArray()).Length - 1;
Since Split takes characters as a param, you could rewrite this by listing the characters being counted directly, as follows:
int count = testString.Split(',', ';', '-').Length - 1;
"this string. contains. 3. dots".Split(new[] {"."}, StringSplitOptions.None).Count() - 1
Edit:
Upon Reading your code more carefully I suggest you do this, you should rephrase your question to
"Check the number of occurences of a certain string in Another string":
string containsString = "this";
string test = "thisisateststringthisisateststring";
var matches = Regex.Matches(test,containsString).Count;
matches is 2!
My initial post answers your actual question "occurrences of a certain character in a string":
string test = "thisisateststring";
int count = test.Count(w => w == 'i');
Count is 3!

How to delete characters and append strings?

I am adding a new record to XML file, first I'm querying all existing items and storing the count in an int
int number = query.count()
and then increment the number by 1.
number = number + 1;
Now I want to format this value in a string having N00000000 format
and the number will occupy the last positions.
Pseudo code:
//declare the format string
sting format = "N00000000"
//calculate the length of number string
int length =number.ToString().Length();
// delete as many characters from right to left as the length of number string
???
// finally concatenate both strings with + operator
???
String output = "N" + String.Format ("00000000", length)
Alternatively if you change your formatstring to "'N'00000000" you can even use:
String output = String.Format (formatString, length)
Which means you can fully specify your output by changing your formatstring without having to change any code.
int i = 123;
string n = "N" + i.ToString().PadLeft(8, '0');
var result = number.ToString("N{0:0000000}");
HTH
You can use the built in ToString overload that takes a custom numeric format string:
string result = "N" + number.ToString("00000000");
Here is a another one ...
result = String.Format("N{0:00000000}",number);

Categories

Resources