Split a string by a character - c#

I have this string here:
String FileNameOrginal = "lighthouse-126.jpg";
and I am trying to split the string into 2, seperating it with "-"
I have tried the following, but I get a syntax error on the Spilt:
String FileNameOrginal = drProduct["productHTML"].ToString();
string[] strDataArray = FileNameOrginal.Split("-");
Please Help, I do not understand what I am doing wrong.

You just need a character instead of string:
string[] strDataArray = FileNameOrginal.Split('-');

So the issue is that you need an array for an input, like this:
string[] strDataArray = FileNameOrginal.Split(
new string[] { "-" },
StringSplitOptions.None);

Instead of:
string[] strDataArray = FileNameOrginal.Split("-");
Try
string[] strDataArray = FileNameOrginal.Split('-');

string FileNameOrginal = "lighthouse-126.jpg";
string file1 = FileNameOrginal.Split('-')[0];
string file2 = FileNameOrginal.Split('-')[1];

Related

String.Split for new lines working with string[] but not with char[]

check this code:
string t = #"\nazerty \n\nazerty \n\nazerty \nazerty";
string[] firstMethod = t.Split(new char[]{'\n'}, StringSplitOptions.RemoveEmptyEntries);
string[] secondMethod = t.Split(new string[]{#"\n"}, StringSplitOptions.RemoveEmptyEntries);
why does first method NOT work and second does ???
Thx
This isn't working because you are using verbatim strings, i.e.:
string t = #"\nazerty \n\nazerty \n\nazerty \nazerty";
... is equivalent to:
string t = "\\nazerty \\n\\nazerty \\n\\nazerty \\nazerty";
It's likely that you actually wanted the following, which uses newline characters instead of literal backslash-n:
string t = "\nazerty \n\nazerty \n\nazerty \nazerty";
This would be "successfully" split on either new[] { "\n" } or new[] { '\n' } (but not new[] { #"\n" } which expects backslash-backslash-n).

Algorithm for filtering top-level directories among a list of paths, C#

Input:
/dir1
/dir1/subdir
/dir1/subdir/sub-subdir
/dir2
Output should be:
/dir1
/dir2
How about this:
string inputDir = "/dir1/subdir/sub-subdir";
string [] Split = inputDir.Split(new Char [] {'/'}, StringSplitOptions.RemoveEmptyEntries);
string outputDir = Split[0];
List<string> result= new List<string>();
foreach (string i in input)
{
string[] tmp = i.split(#"/");
result.add(#"/" + tmp[0]);
}

C# convert DOMAIN\USER to USER#DOMAIN

I currently have the following code:
string user = #"DOMAIN\USER";
string[] parts = user.Split(new string[] { "\\" }, StringSplitOptions.None);
string user = parts[1] + "#" + parts[0];
Input string user can be in one of two formats:
DOMAIN\USER
DOMAIN\\USER (with a double slash)
Whats the most elegant way in C# to convert either one of these strings to:
USER#DOMAIN
Not sure you would call this most elegant:
string[] parts = user.Split(new string[] {"/"},
StringSplitOptions.RemoveEmptyEntries);
string user = string.Format("{0}#{1}", parts[1], parts[0]);
How about this:
string user = #"DOMAIN//USER";
Regex pattern = new Regex("[/]+");
var sp = pattern.Split(user);
user = sp[1] + "#" + sp[0];
Console.WriteLine(user);
A variation on Oded's answer might use Array.Reverse:
string[] parts = user.Split(new string[] {"/"},StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(parts);
return String.Join("#",parts);
Alternatively, could use linq (based on here):
return user.Split(new string[] {"/"}, StringSplitOptions.RemoveEmptyEntries)
.Aggregate((current, next) => next + "#" + current);
You may try this:
String[] parts = user.Split(new String[] {#"\", #"\\"}, StringSplitOptions.RemoveEmptyEntries);
user = String.Format("{0}#{1}", parts[1], parts[0]);
For the sake of adding another option, here it is:
string user = #"DOMAIN//USER";
string result = user.Substring(0, user.IndexOf("/")) + "#" + user.Substring(user.LastIndexOf("/") + 1, user.Length - (user.LastIndexOf("/") + 1));

How to get correct string text?

I'm trying to obtain the correct unicode characters represented by this string:
string originalString = "\u0605\u04c3\u5000\u0000\u5000\ufd00\u4400\ud500\u7600\ud300\u4f00\ubc00\u0c00\u2d00\u4000\ue400\u0e00\u7400\u4800\ub700\u1d00\u1300\ue900\u6000\u4c00\ufb00\u9900\u3900\ud900\u6700\uae00\ueb00\u8f00\u2800\u0200\ub300\u5c00\ufe00\u0100\u3d00\u9100\u3000\u0300\u1600\u0100\u7000\u6200\u8e00\u1d00\u8e00\u6200\ua900\u6300\uc800\u0900\ub700\ub000\u6000\ue400\u9200\u3f00\u9100\u8d00\uef00\u3600\u0100\u9e00\u0081";
If I hard-code it in the cs file, I can see in debug mode that it shows the correct characters, but if I have the exact string written in a file and I try to read it, it shows the string as it is in the file.
TextReader tr = new StreamReader("c:\\test.txt");
string tmpString = tr.ReadLine();
tr.Close();
byte[] array = Encoding.Unicode.GetBytes(tmpString );
string finalResult = Encoding.Unicode.GetString(array);
How can I make the finalResult string have the correct unicode characters?
Thanks in advance
Gonçalo
EDIT: Already tried placing
TextReader tr = new StreamReader("c:\\test.txt",Encoding.Unicode);
but the characters are different from the correct ones.
Does your file actually contain the content:
\u0605\u04c3\u5000\u0000\u5000\ufd00\u4400\ud500\u7600\ud300\u4f00
\ubc00\u0c00\u2d00\u4000\ue400\u0e00\u7400\u4800\ub700\u1d00\u1300
\ue900\u6000\u4c00\ufb00\u9900\u3900\ud900\u6700\uae00\ueb00\u8f00
\u2800\u0200\ub300\u5c00\ufe00\u0100\u3d00\u9100\u3000\u0300\u1600
\u0100\u7000\u6200\u8e00\u1d00\u8e00\u6200\ua900\u6300\uc800\u0900
\ub700\ub000\u6000\ue400\u9200\u3f00\u9100\u8d00\uef00\u3600\u0100\u9e00\u0081
If so, you need to convert each sequence to its corresponding unicode character
string originalString = "\u0605\u04c3\u5000\u0000\u5000\ufd00\u4400\ud500\u7600\ud300\u4f00\ubc00\u0c00\u2d00\u4000\ue400\u0e00\u7400\u4800\ub700\u1d00\u1300\ue900\u6000\u4c00\ufb00\u9900\u3900\ud900\u6700\uae00\ueb00\u8f00\u2800\u0200\ub300\u5c00\ufe00\u0100\u3d00\u9100\u3000\u0300\u1600\u0100\u7000\u6200\u8e00\u1d00\u8e00\u6200\ua900\u6300\uc800\u0900\ub700\ub000\u6000\ue400\u9200\u3f00\u9100\u8d00\uef00\u3600\u0100\u9e00\u0081";
string tmpString = "\\u0605\\u04c3\\u5000\\u0000\\u5000\\ufd00\\u4400\\ud500\\u7600\\ud300\\u4f00\\ubc00\\u0c00\\u2d00\\u4000\\ue400\\u0e00\\u7400\\u4800\\ub700\\u1d00\\u1300\\ue900\\u6000\\u4c00\\ufb00\\u9900\\u3900\\ud900\\u6700\\uae00\\ueb00\\u8f00\\u2800\\u0200\\ub300\\u5c00\\ufe00\\u0100\\u3d00\\u9100\\u3000\\u0300\\u1600\\u0100\\u7000\\u6200\\u8e00\\u1d00\\u8e00\\u6200\\ua900\\u6300\\uc800\\u0900\\ub700\\ub000\\u6000\\ue400\\u9200\\u3f00\\u9100\\u8d00\\uef00\\u3600\\u0100\\u9e00\\u0081";
string finalResult = Regex.Replace(tmpString, #"\\u(....)", match => ((char)int.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber)).ToString());
you can use the Encoding as parameter while reading the file
TextReader tr = new StreamReader("c:\\test.txt",Encoding.Unicode);
string unicode_string = tr.ReadLine();
Try something like:
TextReader streamReader = new StreamReader("c:\\test.txt");
string input = streamReader.ReadLine();
string[] chars = input.Split(new char[] { '\\', 'u' },
StringSplitOptions.RemoveEmptyEntries);
streamReader.Close();
string answer = string.Empty;
foreach (string charachter in chars)
{
byte byte1 = byte.Parse(string.Format("{0}{1}",
charachter[0], charachter[1]), NumberStyles.AllowHexSpecifier);
byte byte2 = byte.Parse(string.Format("{0}{1}",
charachter[2], charachter[3]), NumberStyles.AllowHexSpecifier);
answer += Encoding.Unicode.GetString(new byte[] { byte2, byte1 });
}

parsing a long string in c# and giving those values to parameters

I have this string in C# -
".... School||Abc\r\n...State||CA\r\n..."
The school and state are somewhere in the string. I need to parse the string in such a way that i get the values of School and State for my parameters
string school = abc (from String after parsing)
string state = CA (from string after parsing)
Try this:
string longStr = "School||Abc\r\nState||CA\r\n";
string[] keyValPairs = s.Split("\r\n".ToCharArray());
Dictionary<string, string> info = new Dictionary<string, string>();
foreach(string pair in keyValPairs)
{
string[] split = pair.Split("||");
//split[0] is the key, split[1] is the value
info.Add(split[0], split[1]);
}
Now you can access what you need like so:
string school = info["School"];
string state = info["State"];
Where the longStr variable is just your long string that you start out with, not neccessarily what I set it to.
Try split-ing string on new line chars and then it looks like a dictionary, with key values separated by ||. Another split on "||" should give you what you want.
Back of the envelope code
private static void ParseMyString(string longString) {
IEnumerable<string> shortStrings = longString.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(var ss in shortStrings) {
var kvp = ss.Split("||".ToCharArray());
Console.WriteLine("{0} - {1}", kvp[0], kvp[1]);
}
}
You can use the TextFieldParser class to parse this file, in particular if it is fixed width fields or has known delimiters.
It:
Provides methods and properties for parsing structured text files.
Though it lives in the Microsoft.VisualBasic.Text namespace, it is a .NET assembly and can be used in all .NET projects.
Assuming that your string just contains values separated by "||", "\r" or "\n".
string str = "School||Abc\r\n||State||CA\r\n||AA||AA";
str = str.Trim();
str = str.Replace("\r",string.Empty);
str = str.Replace("\n", string.Empty);
string[] keyValue = str.Split(new string[] { "||" }, StringSplitOptions.None);
Dictionary<string, string> KeyValDic = new Dictionary<string, string>();
for (int i = 0; i < keyValue.Length; i++,i++)
{
KeyValDic.Add(keyValue[i], keyValue[i + 1]);
}

Categories