How can I assign empty to string array in c#?
string [] stack; //string array
how to assign
stack = ""; //this statement gives error cannot implicitly convert to type string to string []
You cannot use:
string[] stack = "";
Since stack in here is an array of string. If you want to initialize empty string for each elements in array, you can use LINQ with Enumerable.Range to get the result, assume there are 10 items in here:
string[] stack = Enumerable.Range(0, 10)
.Select(i => string.Empty)
.ToArray();
This will create an array with three empty strings.
string[] arr1 = new string[] { "", "", "" };
or if you only need one:
string[] arr1 = new string[] { "" };
or another example (with 3 strings):
string[] arr1 = new string[3];
arr1[0] = "";
arr1[1] = "";
arr1[2] = "";
Just iterate over the array like this:
int length = stack.Length;
for(int i = 0; i < length; i++)
{
stack[i] = string.Empty;
}
If you just want to create empty array of string[] object.
string [] stack = new string[]{};
Related
The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}
This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.
So I have a string called today with the value "nick_george_james"
it looks like this
string today = "_nick__george__james_";
how can i isolate the text between the '_' into a new string? i want to get the 3 names into seperate strings so that in the end i have name1, name2, name3 with the values nick, george and james
my application is written in c#
use string.Split
string[] array = today.Split('_');
After editing your question, I realized that you have multiple _ in your string. You should try the following.
string[] array = today.Split("_".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Or
string[] array = today.Split(new []{"_"}, StringSplitOptions.RemoveEmptyEntries);
Later your array will contain:
array[0] = "nick";
array[1] = "george";
array[2] = "james";
string[] array = today.Split('_');
name1=array[0];
name2=array[1];
name3=array[2];
Thought of coming up with an idea other than string.Split.
string today = "_nick__george__james_";
//Change value nNoofwordstobeFound accordingly
int nNoofwordstobeFound = 3;
int nstartindex = 0;
int nEndindex = 0;
int i=1;
while (i <= nNoofwordstobeFound)
{
Skip:
nstartindex = today.IndexOf("_",nEndindex);
nEndindex = today.IndexOf("_", nstartindex + 1);
string sName = today.Substring(nstartindex + 1, nEndindex - (nstartindex + 1));
if (sName == "")
{
goto Skip;
}
else
{
//Do your code
//For example
string abc= sName;
}
i++;
}
I'd still prefer string.split method over this anytime.
string[] nameArray = today.Split('_');
Here you will get a array of names. You can get each name from by specifying index positions of the nameArray.
ie Now the the nameArray contains values as below
nameArray[0] = "nick", nameArray[1] = "george", nameArray[2] = "james"
string[] chkItems = new string[4];
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
itemCount = ltbxInterests.SelectedItems.Count;
for (int i = 0; i <= itemCount; i++)
{
ltbxInterests.SelectedItems.CopyTo(chkItems, 0);
// here it is returning an exception
//"Object cannot be stored in an array of this type."
}
Please help me how to get out from this exception
Couple issues here, chkItems is defined as length 4 so you will get an exception if you try and put more than 4 items in. The source array SelectedItems is of type object so you would need to cast the result.
Assuming you are only putting strings into the listbox you could use (remember to reference System.Linq)
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().ToArray();
If you are wanting to limit to the first 4 items, you could replace the last line to
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().Take(4).ToArray();
Also you could shorten the code to use an array initializer (but this wil make str length 3 because you only have 3 items):
string[] str = new [] {
txtID.Text,
txtName.Text,
txtEmail.Text,
}
SelectedItems is a collection of Object, then, in order to use CopyTo methods, chkItems must be an array of type object (i.e. object[]).
Otherwise, you can use LINQ to convert, for example, to a list of strings:
var selectedList = ltbxInterests.SelectedItems.OfType<object>()
.Select(x => x.ToString()).ToList();
You chould check the Type of > chkItems .
Here is the requirement.
I have a string with multiple entries of a particular format. Example below
string SourceString = "<parameter1(value1)><parameter2(value2)><parameter3(value3)>";
I want to get the ouput as below
string[] parameters = {"parameter1","parameter2","parameter3"};
string[] values = {"value1","value2","value3"};
The above string is just an example with 3 pairs of parameter values. The string may have 40, 52, 75 - any number of entries (less than 100 in one string).
Like this I have multiple strings in an array. I want to do this operation for all the strings in the array.
Could any one please advice how to achieve this? I'm a novice in c#.
Is using regex a better solution or is there any other method?
Any help is much appreciated.
If you didn't like RegEx's you could do something like this:
class Program
{
static void Main()
{
string input = "<parameter1(value1)>< parameter2(value2)>";
string[] Items = input.Replace("<", "").Split('>');
List<string> parameters = new List<string>();
List<string> values = new List<string>();
foreach (var item in Items)
{
if (item != "")
{
KeyValuePair<string, string> kvp = GetInnerItem(item);
parameters.Add(kvp.Key);
values.Add(kvp.Value);
}
}
// if you really wanted your results in arrays
//
string[] parametersArray = parameters.ToArray();
string[] valuesArray = values.ToArray();
}
public static KeyValuePair<string, string> GetInnerItem(string item)
{
//expects parameter1(value1)
string[] s = item.Replace(")", "").Split('(');
return new KeyValuePair<string, string>(s[0].Trim(), s[1].Trim());
}
}
It might be a wee bit quicker than the RegEx method but certainly not as flexible.
You could use RegEx class in combination with an expression to parse the string and generate these arrays by looping through MatchCollections.
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
This does it:
string[] parameters = null;
string[] values = null;
// string SourceString = "<parameter1(value1)><parameter2(value2)><parameter3(value3)>";
string SourceString = #"<QUEUE(C2.BRH.ARB_INVPUSH01)><CHANNEL(C2.MONITORING_CHANNEL)><QMGR(C2.MASTER_NAME.TRACKER)>";
// string regExpression = #"<([^\(]+)[\(]([\w]+)";
string regExpression = #"<([^\(]+)[\(]([^\)]+)";
Regex r = new Regex(regExpression);
MatchCollection collection = r.Matches(SourceString);
parameters = new string[collection.Count];
values = new string[collection.Count];
for (int i = 0; i < collection.Count; i++)
{
Match m = collection[i];
parameters[i] = m.Groups[1].Value;
values[i] = m.Groups[2].Value;
}