String to array - c#

I have a string :
id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx
I just need the value for idX-value from the string into array.
How can I achieve it?

The simple way, the value is in position (4x - 1):
var list = input.Split(':');
var outputs = new List<string>();
for (int index = 0; index < list.Count(); index++)
{
if (index % 4 == 3)
outputs.Add(list.ElementAt(index));
}

Use String.Split()
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
String myString = "id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx";
String[] tokens = myString.Split(new Char[] {':'});
The token array will contain {"id0","xxxxx","id0-value","xxxxx","id1","xxxxxxxx","id1-value","xxxxx","id3","xxxxxxxx","d3-value","xxx"}
The second possibility is to use String.IndexOf() and String.Substring().
http://msdn.microsoft.com/en-us/library/5xkyx09y
http://msdn.microsoft.com/en-us/library/aka44szs
Int start = 0;
ArrayList tokens;
while((start = myString.IndexOf("-value:", start)) > -1) {
ArrayList.Add(myString.Substring(start+6, myString.IndexOf(":", start+7);
start += 6; // Jump past what we just found.
}

Split it using a Regex(a regex which splits : coming after x), then split using colon : and use first index as a Dictionary Key and Second index as Dictionary value.

Related

C# Array Different indexes

Hi i want to search for character in a string array but i need to search Between 2 indices. For example between index 2 and 10. How can I do that?
foreach (var item in currentline[2 to 10])
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
As you can see, foreach enumerates over a collection or any IEnumerable.
As the comments say, you can use a for loop instead, and pick out the elements you want.
Alternatively, since you want to search for a character in a string, you can use IndexOf, using the start index and count overload to find where a character is.
As there is no use of the c++ in your code I will assume that it's a vestige of code.
You can simply addess your issue like this:
In the currentline
Take char from index 2 to 10
Till you find a char you don't want.
concatenate the resulting char array to a string.
Resulting Code:
var data = "##";//01234567891 -- index for the string below.
var currentline= "kj[abcabc;z]Selected data will be between: '[]';";
var exceptChar = ",;";
data += new string(
input.Skip(3)
.Take(8)
.TakeWhile(x=> !exceptChar.Contains(x))
.ToArray()
);
There is a string method called string.IndexOfAny() which will allow you to pass an array of characters to search for, a start index and a count. For your example, you would use it like so:
string currentLine = ",;abcde;,abc";
int index = currentLine.IndexOfAny(new[] {',', ';'}, 2, 10-2);
Console.WriteLine(index);
Note that the last parameter is the count of characters to search starting at the specified index, so if you want to start at index 2 and finish at index 10, the count will be finish-start, i.e. 10-2.
You can search for characters in strings and get their indexes with this LINQ solution:
string str = "How; are, you; Good ,bye";
char[] charArr = { ',', ';' };
int startIndex = 2;
int endIndex = 10;
var indexes = Enumerable.Range(startIndex, endIndex - startIndex + 1)
.Where(i=>charArr.Contains(str[i]))
.ToArray();
In this case we get Enumerable.Range(2, 9) which generates a sequence between 2 and 10 and the Where clause filters the indexes of the characters in str that are matching one of the characters inside charArr.
Thanks everey one finaly i fixed it by your guid thanks all
myarr = new mytable[50];
number_of_records = 0;
number_of_records = fulllines.Length;
for (int line = 1; line < fulllines.Length; line++)
{
int c = 0;
for (int i = 0; i < record_lenth; i++)
{
string data = "";
string currentline = fulllines[line];
string value = "";
for (int x = c; x < fulllines[line].Length; x++)
{
value += currentline[x];
}
foreach (var item in value)
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
}
}

Getting error while using split method for reading multiple integers in a single line

I am getting an error while using Split while reading an integer from the user
int[] a = new int[s];
for (i = 0; i < s; i++)
{
a[i] = Int32.Parse(Console.ReadLine().Split(' '));
}
Can you please help me how to use Split.
LINQ can really help you here:
int[] a = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
Since split returns an array, and each time you need the i'ed one, you should change it like this:
int[] a = new int[s];
string[] input = Console.ReadLine().Split(' ');
for (i = 0; i < s; i++)
{
a[i] = Int32.Parse(input[i]);
}
You need to read the input only once btw.
Like #loneshark99 said it would be even better to use TryParse(). Since that returns a boolean, you can check if the input are indeed integers. If you just use Parse and they are not integers, it would throw an exception.
Code with TryParse():
int[] a = new int[s];
string[] input = Console.ReadLine().Split(' ');
for (i = 0; i < s; i++)
{
if (Int32.TryParse(input[i], out a[i]))
{
//successfully parsed
}
}
The if-statement is not necessary but it's just to point out how you could use the TryParse.
We can take the input as string first
string[] array_temp = Console.ReadLine().Split(' ');
and then convert the array into Int
int[] array = Array.ConvertAll(array_temp,Int32.Parse);

How to append every X in c# stringbuilder

I'm using unity and c# and am not sure how to use stringbuilder to append a "/" every X characters. I have code and can build a string from a array with the code below, and add a comma after each string, but i need to add the "/" after every x string
it should for example convert "122342" to "1,2,2,/,3,4,2". Currently it would convert it to "1,2,2,3,4,2"
this is the code i have already
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
Builtstring.Append(griditem).Append(",");
}
built = Builtstring.ToString();
Use a FOR loop and then check if the character is a factor of some desired nTH character. If so add an extra '/'.
int x = 2; // your x
StringBuilder builtstring = new StringBuilder();
for (int i = 0; i < tobuild.Length; i++)
{
string item = tobuild[i];
builtstring.Append(item).Append(",");
if (i%x==0) { builtstring.Append("/"); }
}
string built = builtstring.ToString();
Add an if statement to evaluate the character and then act accordingly.
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(griditem == 'x') { Builtstring.Append(griditem).Append(#"/"); }
Builtstring.Append(griditem).Append(",");
}
built = Builtstring.ToString();
Or if you actually want to count a certain number of characters before putting a slash you can do this.
int count = 10;
int position = 0;
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(position == count) { Builtstring.Append(griditem).Append(#"/"); position = 0; }
else{Builtstring.Append(griditem).Append(","); position++;}}
built = Builtstring.ToString();
You can iterate over the array of strings using a for loop, which provides an index.
For each iteration, add the current String to the StringBuilder, in addition to a ',' in case we still didn't reach the last string in the array.
Also, after x strings add a '/'. We can know that we reached x strings using the % (modulus) operator.
Notice that I start the loop from index = 1. I do that because the modulus operator for the value 0 with any positive number will yield 0, which will add the '/' char after the first word, something that we don't necessarily want.
static void Insert(StringBuilder b, int x, string[] tobuild)
{
for(var index = 1; index < tobuild.Length; ++index)
{
b.Append(tobuild[index]);
if(index != tobuild.Length -1)
{
b.Append(",");
}
if(0 == index % x)
{
b.Append("/");
}
}
}

Extract string list from a long string using prefix pattern in C#

I have a very big string with a lot of usernames. I want to extract the names from the string. That means I have one big string with lot of names in it. At the end I want every username in a string array.
An example of the string:
blablablabla#User;\u0004User\username,blablablablablablablabla#User;\u0004User\anotherusername,#Viewblablablablablablablabla
Search for: u0004User\
Save all charractes until , is found in the string array
Pseudocode:
string [] array = new string []{};
int i = 0;
foreach (var c in bigdata)
{
if(c == "u0004User\")
{
array[i] = c.AllCharactersUntil(',');
i++;
//AllCharactersUntil is a pseudo function
}
}
You can use string.IndexOf to find the index of "u0004User\" then again to find the following comma. Then use string.Substring to get the name. Keeping track of the current index and using it to tell IndexOf where to start searching from.
string bigdata =
#"blablablabla#User;\u0004User\username,blablablablablablablabla#User;\u0004User\anotherusername,#Viewblablablablablablablabla";
string searchValue = #"u0004User\";
int index = 0;
List<string> names = new List<string>();
while (index < bigdata.Length)
{
index = bigdata.IndexOf(searchValue, index);
if (index == -1) break;
int start = index + searchValue.Length;
int end = bigdata.IndexOf(',', start);
if (end == -1) break;
names.Add(bigdata.Substring(start, end - start));
index = end + 1;
}
Console.WriteLine(string.Join(", ", names));
That will give you the following output
username, anotherusername
NOTE
I've assumed that the "\u0004" values are those 6 characters and not a single unicode character. If it is a unicode character then you need the following change
string searchValue = "\u0004User\\";
Here's a simple result:
string input = "blablablabla#User;\\u0004User\username,blablablablablablablabla#User;\\u0004User\anotherusername,#Viewblablablablablablablabla";
List<string> userNames = new List<string>();
foreach (Match match in Regex.Matches(input, #"(u0004User\\)(.*?),", RegexOptions.IgnoreCase))
{
string currentUserName = match.Groups[2].ToString();
userNames.Add(currentUserName); // Add UserName to List
}

Insert blank strings into array based on index

Let's say I have an array for example
string[] A = {"1","2","3","4","5"}
I want the array to be of size 10, and want to insert blank strings after a certain index.
For example, I could make it size 10 and insert strings after index 3 which would result in
A = {"1","2","3","4","","","","","","5"}
Basically the elements after the given index will be pushed to the end and blank strings will take the empty space in between.
This is what I tried but it only adds one string and doesnt exactly set a size for the array
var foos = new List<string>(A);
foos.Insert(33, "");
foos[32] = "";
A = foos.ToArray();
You can use InsertRange
var l = new List<string>{"1","2","3","4","5"};
l.InsertRange(3, new string[10 - l.Count]);
foreach(var i in l)
Console.WriteLine(i);
Note: The above doesn't populate with empty strings but null values, but you can easily modify the new string[] being used to be populated with your desired default.
For example; see How to populate/instantiate a C# array with a single value?
Here is LINQ based approach:
public string[] InsertToArray(string[] array, int index, int newArrayCapacity)
{
var firstPart = array.Take(index + 1);
var secondPart = array.Skip(index + 1);
var newPart = Enumerable.Repeat(String.Empty, newArrayCapacity - array.Length);
return firstPart.Concat(newPart).Concat(secondPart).ToArray();
}
Here is the usage of the method:
string[] A = {"1","2","3","4","5"};
// Insert 5 elements (so that A.Length will be 10) in A after 3rd element
var result = InsertToArray(A, 3, 10);
Added: see Sayse's answer, really the way to go
Since arrays are fixed sized collections, you can't resize an array.What you need to do is to split your array elements, you need to get the elements before and after the specified index,you can do that by using Skip and Take methods, then you need to generate a sequence of empty strings and put them together:
string[] A = {"1","2","3","4","5"};
int index = 3;
var result = A.Take(index + 1)
.Concat(Enumerable.Repeat("", 10 - A.Length))
.Concat(A.Skip(index+1))
.ToArray();
If you don't mind using a list instead of an array, you can do it this way:
int index = 3;
int numberOfBlanksToInsert = 5;
List<string> strings = new List<string>();
for (int i = 0; i < numberOfBlanksToInsert; i++)
{
strings.Insert(index, "");
}
You can also output this to an array when you're done:
string[] A = strings.ToArray();
static string[] InsertRange(string[] initialValues, int startIndex, int count, string toInsert)
{
string[] result = new string[initialValues.Length + count];
for (int i = 0; i < initialValues.Length + count; i++)
result[i] = i < startIndex ? initialValues[i] : i >= startIndex + count ? initialValues[i - count] : toInsert;
return result;
}
Usage : InsertRange(A, 4, 5, "hello");
Output : "1, 2, 3, 4, hello, hello, hello, hello, hello, 5"

Categories

Resources