How to convert string to string array[] in c# - c#

i have a string variable which receives data from web the data is in the from of string like this
string output="[1,2,3,4,5,6,7,8,9,0]";
i want to convert it into a string array [] so that i can specify each element via for each loop
string output;
into
string[] out;
PS: if any predefined method is there that will also help

You can do that using Trim And Split:
var out = output.TrimStart('[').TrimEnd(']').Split(',');
But your data looks like JSON string. So, if you are dealing with JSON instead of making your own parser try using libraries that already does that such as JSON.NET.

You can use Trim functions to remove brackets and then use Split() function to get the string array that contains the substrings in this string that are delimited by elements of a specified Unicode character.
var res = output.TrimStart('[')
.TrimEnd(']')
.Split(',');

string[] arr = output.Where(c => Char.IsDigit(c)).Select(c => c.ToString()).ToArray();

output.Substring(1, output.Length - 2).Split(',');

Related

Converting string array to char array

I want to read .txt file, extract every distinct from it and save it to array. So far I came up with this:
string text = File.ReadAllText(#"C:\Users\ASUS\Desktop\szyfrowanie\TextSample.txt");
string uniqueLetters = new string(text.Distinct().ToArray());
I couldn't find any way to save those distinct letters to a char array. Now I want to convert the uniqueLetters array to a char array. I've been trying through certain things like creating a new char[] array and assigning uniqueLetter value in a for loop. ToCharArray() also failed me. Does anybody have any ideas how to do it?
The ToArray method returns a char[], that is, a char array. Use it like this in your code:
string text = File.ReadAllText(#"C:\Users\ASUS\Desktop\szyfrowanie\TextSample.txt");
char[] uniqueLetters = text.Distinct().ToArray();
The return value type is char array and not string.
string text = "AABBCC";
var uniqueLetters = text.Distinct().ToArray();
Output (array of chars):
A, B, C.
Edit:
Dont forget:
using System.Linq;

How to store text from a file-list into a variable in c#

Hi I am new to programming. I would like to read a text file and take the values ( strings ) and store each character of the string in an array individually. I have used a list to take in the vales from the text file. I am finding it difficult to move them into an array and then use those values in my program. Please find me a solution if possible. Thanking you in advance.
public class file_IO
{
string[] letters = new string[] //I would like to store it in this variable
public void File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
foreach (string line in file_lines)
{
}
}
}
Hope this will work for you!.
public char[] File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
StreamReader sr = new StreamReader(filepath);
string fileContentInString = sr.ReadToEnd();
sr.Close();
return fileContentInString.ToCharArray();
}
List<List<char>> linesAsChars = File.ReadAllLines(filepath)
.Select(l => l.ToList())
.ToList();
This will get a List of List of chars.
string implements IEnumerable<char>, so with ToList each line in the file is translated to List<char>.
Solution to "store each character of the string in an array individually" is fairly easy because string is in fact an array of char. You can do this using something like this :
char[] letters;
public void File_Reader()
{
string filepath = #"env.txt";
letters = File.ReadAllText(filePath).ToArray();
}
I'm not really sure if I have understood your question properly, but from what I have read, I will assume that you want an array of lines (which are strings).
In this case, you don't need to do much as the File.ReadAllLines() method naturally outputs an array of string variables.
Remove the for loop and replace
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
with:
letters = File.ReadAllLines(filepath)
In case what you want is actually an array of every char value in your file, I would refer to #m.rogalski's answer and declare an array of char[], for example, declare:
char[] fileChars;
and then replace the line I mentioned earlier with:
fileChars = readAllText(filePath).toCharArray()
You will notice that you do not need a loop in either of the above situations. Hope I helped.

C# Cannot implicitly convert type 'string' to 'string[]' within an if else statement

I am trying to read a string into an array and I get the error "Cannot implecitly convert type 'string' to 'string[]'.
The error occurs here:
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
My full if else statement is below:
if (!string.IsNullOrEmpty(result.Tables[0].Rows[0].Field<string>("WebHTML")))
{
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
NewsContent.Text = sepText[1];
if (!string.IsNullOrEmpty(sepText[0]))
Image1.ImageUrl = sepText[0];
else
Image1.Visible = false;
NewsTitle.Text = String.Format("{3}", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat(), result.Tables[0].Rows[0].Field<string>("Title"));
Hyperlink1.NavigateUrl = String.Format("{0}/news/{1}/{2}.aspx", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat());
}
else
{
Hyperlink1.Visible = false;
Image1.Visible = false;
}
Thank you for your help!
EDIT Code for URL Decode:
public static string UrlDecode(this string str)
{
return System.Web.HttpUtility.UrlDecode(str);
}
result.Tables[0].Rows[0].Field<string>("WebHTML") is going to give you the value of the WebHTML field in the first row in the first table which is a single string rather than a string[].
You may want to show your code for UrlDecode() since it looks like a custom implementation rather than one of the built-in framework versions.
You also declare the UrlDecode method to take a string as a parameter and return a string. Remember, a string is not the same thing as a string array.
It seems that you are trying to put:
result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
which returns a string, into an array of strings.
Simply delare your sepText variable as a string rather than a string array and you should be good to go, e.g.:
string sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
Later in your code you will clearly need to read the contents of the string like this:
Image1.ImageUrl =sepText;
Assuming the UrlDecode you are using is the one from here then the result is a string and not a string[] !
UrlDecode returns a string and you are assigning it to an array.
If you want the parts you will have to use the string to create an Url object.
Url url = new Url(result.Tables[0].Rows[0].Field<string>("WebHTML"));
and then get the parts.
See: Get url parts without host
I don't think URLDecode works the way you think it works. All URLDecode does is remove URL encoding from a string. It does not return an array of strings - only the decoded value of the string you gave it.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx
Example: Your web browser replaces a space with %20. This changes the %20 back to a space.
That's because the result of this line is "string" and you're trying to assign it to an array since UrlDecode do not produce an array. What you probably wanted is to use a method split() to create an array of separators?

Pass an array to a function (And use the function to split the array)

I want to pass a string array (separated by commas), then use a function to split the passed array by a comma, and add in a delimiter in place of the comma.
I will show you what I mean in further detail with some broken code:
String FirstData = "1";
String SecondData = "2" ;
String ThirdData = "3" ;
String FourthData = null;
FourthData = AddDelimiter(FirstData,SecondData,ThirdData);
public String AddDelimiter(String[] sData)
{
// foreach ","
String OriginalData = null;
// So, here ... I want to somehow split 'sData' by a ",".
// I know I can use the split function - which I'm having
// some trouble with - but I also believe there is some way
// to use the 'foreach' function? I wish i could put together
// some more code here but I'm a VB6 guy, and the syntax here
// is killing me. Errors everywhere.
return OriginalData;
}
Syntax doesn't matter much here, you need to get to know the Base Class Library. Also, you want to join strings apparently, not split it:
var s = string.Join(",", arrayOFStrings);
Also, if you want to pass n string to a method like that, you need the params keyword:
public string Join( params string[] data) {
return string.Join(",", data);
}
To split:
string[] splitString = sData.Split(new char[] {','});
To join in new delimiter, pass in the array of strings to String.Join:
string colonString = String.Join(":", splitString);
I think you are better off using Replace, since all you want to do is replace one delimiter with another:
string differentDelimiter = sData.Replace(",", ":");
If you have several objects and you want to put them in an array, you can write:
string[] allData = new string[] { FirstData, SecondData, ThirdData };
you can then simply give that to the function:
FourthData = AddDelimiter(allData);
C# has a nice trick, if you add a params keyword to the function definition, you can treat it as if it's a function with any number of parameters:
public String AddDelimiter(params String[] sData) { … }
…
FourthData = AddDelimiter(FirstData, SecondData, ThirdData);
As for the actual implementation, the easiest way is to use string.Join():
public String AddDelimiter(String[] sData)
{
// you can use any other string instead of ":"
return string.Join(":", sData);
}
But if you wanted to build the result yourself (for example if you wanted to learn how to do it), you could do it using string concatenation (oneString + anotherString), or even better, using StringBuilder:
public String AddDelimiter(String[] sData)
{
StringBuilder result = new StringBuilder();
bool first = true;
foreach (string s in sData)
{
if (!first)
result.Append(':');
result.Append(s);
first = false;
}
return result.ToString();
}
One version of the Split function takes an array of characters. Here is an example:
string splitstuff = string.Split(sData[0],new char [] {','});
If you don't need to perform any processing on the parts in between and just need to replace the delimiter, you could easily do so with the Replace method on the String class:
string newlyDelimited = oldString.Replace(',', ':');
For large strings, this will give you better performance, as you won't have to do a full pass through the string to break it apart and then do a pass through the parts to join them back together.
However, if you need to work with the individual parts (to recompose them into another form that does not resemble a simple replacement of the delimiter), then you would use the Split method on the String class to get an array of the delimited items and then plug those into the format you wish.
Of course, this means you have to have some sort of explicit knowledge about what each part of the delimited string means.

String Array And a String Parameter

I"m developing a simple application that have a line like this:
string[] values = ReadAll(inputFile);
As inputFile is a string, but how I can do this without conflicts(Cannot implicitly convert type 'string' in 'string[]')?
Assuming your ReadAll method has a signature like this
string ReadAll(string inputFile);
then the problem is not with inputFile but with the return value of the method which cannot be assigned to a string[].
Are you maybe looking for File.ReadAllLines?
string[] values = File.ReadAllLines(inputFile);
Or do you want to split a string by some delimeter?
string[] values = ReadAll(inputFile).Split('\n');
Based on the exception message you gave us, ReadAll(inputFile) returns a string, and you assign it to a string[], so that's why it doesn't work.
This would work:
string input = ReadAll(inputFile);
After this do you want to split the strings in some way? We'd need more details to help you further.

Categories