String.Split issues - c#

The strings I try to initialize with temp.Split results are always null.
G.ReadLine() is simply a "name%path" format. I also changed the encoding to unicode for certainty that there is no encoding difference between file and program.
Here is the relevant fragment:
StreamReader g = new StreamReader(path + "database.txt",Encoding.Unicode);
do
{
String temp;
temp = g.ReadLine();
//wr.WriteLine(temp);
try
{
names[ii] = temp.Split('%')[0];
Thank you for help

So now we found the route of the problem.
The instantiation of names was wrong.
Instead of
string[] names = null;
Something like
string[] names = new string[5];
must be used. The Problem here is that you have to now before how many strings the array will contain.
I recommand you to use an List of strings so something like that:
List<string> names = new List<string>();
and then use it with:
names.Add(temp.Split('%')[0]);

"name%path".Split('%')[0] returns "name"
So the problem is not Split function, but in temp which value does not have "name%path" pattern.

Related

convert json string to string array

I'm trying to convert a json string to a string array
my json string: "[\"false\",\"true\"]"
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
string[] strArray = new string[2];
strArray = js.Deserialize("[\"false\",\"true\"]", string[2]).ToArray();
but it only allows me to do a charArray.
I just need to be able to call my result as strArray[0] so that it will return "false"
Try doing:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Your example code wouldn't compile. The second parameter should be a Type object, which string[2] isn't. It should be this:
strArray = js.Deserialize("[\"false\",\"true\"]", typeof(string[]));
Or, as the other answer mentioned, you can use the other, generic overload for the method:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Either one will do exactly the same thing. It's just handy to be able to pass a Type object sometimes if you don't know beforehand what the actual type will be. In this case you do, so it doesn't matter.
Why not use Newtonsoft's JArray type? It is built for this conversion and can handle many edge cases automatically.
var jArray = JArray.Parse("[\"false\",\"true\"]");
var strArray = jArray.ToObject<string[]>()
This will give you a string array. But you could also elect to use .ToArray() to convert to a JToken array which can sometimes be more useful.

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.

Why is Resharper telling me my string[] is never assigned?

On this declaration:
string[] TardyEvenEmorys;
...Resharper tells me, "Field 'TardyEvenEmorys' is never assigned."
Later on in the code, assignments are made to the string[]:
TardyEvenEmorys[1] = string.Empty;
TardyEvenEmorys[2] = string.Empty;
TardyEvenEmorys[3] = string.Empty;
TardyEvenEmorys[4] = string.Empty;
...and then actual values are conditionally added:
foreach (KeyValuePair<int, string> entry in itemNumberTardyPairs)
{
TardyEvenEmorys[entry.Key] = entry.Value;
. . .
...finally, those values are used in this way:
string url = GetTardyFilename(TardyEvenEmorys[Number]);
So what is Resharper telling me? That I should instantiate the string[] on declaration, or...???
You're assigning individual elements of the array, but never actually creating the array itself.
So what is Resharper telling me? That I should instantiate the string[] on declaration, or...???
You need to instantiate the array somewhere. This could be during the declaration, or later. For example, to do it during the declaration, you would need to add:
string[] TardyEvenEmorys = new string[5]; // Some appropriate length
Without this, the first time you assign one of the elements, you'll get an exception since the array is null.
You are missing following code somewhere and should be getting null pointer exception:
TardyEvenEmorys = new string[22];

string.insert multiple values. Is this possible?

Im still learning in C#, and there is one thing i cant really seem to find the answer to.
If i have a string that looks like this "abcdefg012345", and i want to make it look like "ab-cde-fg-012345"
i tought of something like this:
string S1 = "abcdefg012345";
string S2 = S1.Insert(2, "-");
string S3 = S2.Insert(6, "-");
string S4 = S3.Insert.....
...
..
Now i was looking if it would be possible to get this al into 1 line somehow, without having to make all those strings.
I assume this would be possible somehow ?
Whether or not you can make this a one-liner (you can), it will always cause multiple strings to be created, due to the immutability of the String in .NET
If you want to do this somewhat efficiently, without creating multiple strings, you could use a StringBuilder. An extension method could also be useful to make it easier to use.
public static class StringExtensions
{
public static string MultiInsert(this string str, string insertChar, params int[] positions)
{
StringBuilder sb = new StringBuilder(str.Length + (positions.Length*insertChar.Length));
var posLookup = new HashSet<int>(positions);
for(int i=0;i<str.Length;i++)
{
sb.Append(str[i]);
if(posLookup.Contains(i))
sb.Append(insertChar);
}
return sb.ToString();
}
}
Note that this example initialises StringBuilder to the correct length up-front, therefore avoiding the need to grow the StringBuilder.
Usage: "abcdefg012345".MultiInsert("-",2,5); // yields "abc-def-g012345"
Live example: http://rextester.com/EZPQ89741
string S1 = "abcdefg012345".Insert(2, "-").Insert(6, "-")..... ;
If the positions for the inserted strings are constant you could consider using string.Format() method. For example:
string strTarget = String.Format("abc{0}def{0}g012345","-");
string s = "abcdefg012345";
foreach (var index in [2, 6, ...]
{
s = s.Insert(index, "-");
}
I like this
StringBuilder sb = new StringBuilder("abcdefg012345");
sb.Insert(6, '-').Insert(2, '-').ToString();
String s1 = "abcdefg012345";
String seperator = "-";
s1 = s1.Insert(2, seperator).Insert(6, seperator).Insert(9, seperator);
Chaining them like that keeps your line count down. This works because the Insert method returns the string value of s1 with the parameters supplied, then the Insert function is being called on that returned string and so on.
Also it's worth noting that String is a special immutable class so each time you set a value to it, it is being recreated. Also worth noting that String is a special type that allows you to set it to a new instance with calling the constructor on it, the first line above will be under the hood calling the constructor with the text in the speech marks.
Just for the sake of completion and to show the use of the lesser known Aggregate function, here's another one-liner:
string result = new[] { 2, 5, 8, 15 }.Aggregate("abcdefg012345", (s, i) => s.Insert(i, "-"));
result is ab-cd-ef-g01234-5. I wouldn't recommend this variant, though. It's way too hard to grasp on first sight.
Edit: this solution is not valid, anyway, as the "-" will be inserted at the index of the already modified string, not at the positions wrt to the original string. But then again, most of the answers here suffer from the same problem.
You should use a StringBuilder in this case as Strings objects are immutable and your code would essentially create a completely new string for each one of those operations.
http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx
Some more information available here:
http://www.dotnetperls.com/stringbuilder
Example:
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("abcdefg012345");
sb.Insert(2, '-');
sb.Insert(6, '-');
Console.WriteLine(sb);
Console.Read();
}
}
}
If you really want it on a single line you could simply do something like this:
StringBuilder sb = new StringBuilder("abcdefg012345").Insert(2, '-').Insert(6, '-');

how to change nth element of the string

i have a code in c# like below
string s = new string('~',25);
int ind = 5;
s[ind] = 'A';
it gives an error
Property or indexer 'string.this[int]' cannot be assigned to -- it is read
so what is the problem, and how can i fix it.
Strings are immutable - you can't change an existing one.
Two options:
Use StringBuilder, e.g.
StringBuilder builder = new StringBuilder(new string('~', 25));
builder[5] = 'A';
string result = builder.ToString();
Build a new string from a char array:
char[] chars = new string('~', 25).ToCharArray();
chars[5] = 'A';
string result = new string(chars);
In both cases you could populate the mutable data without building a new string to start with if you want - that would involve more code, but would probably be more efficient.
Alternatively, you can take substrings and concatenate them together, as per another answer ...there are basically lots of ways of tackling this. Which one is appropriate will depend on your actual use case.
Following MSDN:
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.
Take a look at StringBuilder class or use char array instead.
C# strings are immutable which means that once constructed the cannot be changed. Try using an array of chars instead.
Try
s = s.Substring(0, ind) + "A" + s.Substring(ind + 1);
You can use Stringbuilder, in which you can assign to the indexer:
StringBuilder sb = s;
int ind = 5;
sb[ind] = 'A';
s = sb.ToString();

Categories