I am using ASP.NET Web Pages to create a project in which I am assigned to place each character of the user's (customer's) name in each seperate input block.
For that I am getting the value from the Sql Server CE Database and then I am trying to convert it into an array of one character for each input. I have tried the following code for that
var form_data = db.QuerySingle("SELECT * FROM Form_Data WHERE Form_Id =#0", form_id);
var name_emp = form_data.Name_Emig;
if(name_emp != null) {
name_emp = name_emp.ToString().Split('');
}
It generates the following Compiler error:
http://msdn.microsoft.com/en-us/library/8eb78ww7(v=vs.90).aspx (Compiler error: CS1011)
Which means that the character cannot be initialized by an empty value. I want to convert that value in one character each array.
The name is as: Afzaal Ahmad Zeeshan. So, in each input it would be placed inside the value of it. But the code I am using isn't working. Any suggestion to split the string at each character, so the result would be
{'A', 'F', 'Z', 'A', 'A', 'L' ...}
It doesn't matter whether result is Capital case or lower case. I will convert it to the desired one later.
You can try using ToCharArray().
So your code would be this:
var form_data = db.QuerySingle("SELECT * FROM Form_Data WHERE Form_Id =#0", form_id);
var name_emp = form_data.Name_Emig;
if(name_emp != null) {
name_emp = name_emp.ToCharArray();
}
You can use this to iterate with each item :
string yourString = "test";
foreach(var character in yourString)
{
// do something with each character.
}
Or this to get all characters in a char[]
char[] characters = yourstring.ToCharArray();
Try name_emp.ToArray(). A string implements IEnumerable<char>, so ToArray will return an array of the char.
Edit:
Actually I suppose ToCharArray is better in this case...
Related
I have an array of names concatenated with an _ ex: string[] samples = ["Test_test","Test2_blah", "Test3_"].
At some point in my code I want to try and validate the value after the _ to check if it's empty or null, and if it is, remove it from the array like so :
string[] splitSample= samples[2].Split(new char[] { '_' }, 2);
if(!string.IsNullOrWhiteSpace(splitSample[1]))
The problem i'm running into is that splitSample[1] is "", when i check the length of the string it's 1, not 0 but in Visual Studio 2017 it shows empty quotes. Is there a way to actually see the value that's invisible or what's actually going on?
EDIT:
Here's a pic of the immediate window when i check the array value
Depending on how they get rendered, some Unicode characters can be invisible (i.e., "") when represented (e.g., "\u200C", "\u2063", and check this answer for more).
Now, your string has a length (>0), and you'd like to know what it actually represents. There are many ways to achieve this, one of them is to convert your string to hex. Here's an example using the Unicode character mentioned above:
static void Main(string[] args)
{
string invisibleChar = "\u200C";
string[] samples = { "Test_test", "Test2_blah", "Test3_" + invisibleChar };
string[] splitSample = samples[2].Split(new char[] { '_' }, 2);
// Prints "Test3_" (or "Test3_?" if you use Console.Write).
Debug.Print(samples[2]);
Debug.Print(splitSample.Length.ToString()); // 2
if (!string.IsNullOrWhiteSpace(splitSample[1]))
{
Debug.Print(splitSample[1].Length.ToString()); // 1
// Prints "" (or "?" in Console).
Debug.Print(splitSample[1]);
var hex = string.Join("", splitSample[1].Select(c => ((int)c).ToString("X2")));
// Prints "200C"
Debug.Print(hex);
}
Console.ReadLine();
}
Note that because you're using !string.IsNullOrWhiteSpace, you could be missing other Unicode characters (e.g., "\u00A0") because they're considered a white space. So, you should ask yourself whether you want to also check for these or not.
Hope that helps.
I have a bit of a weird question here at hands. I have a text that's encoded in such a way that each character is replaced by another character and I'm creating an application that will replace each character with a correct one. But I've come across a problem that I have trouble solving. Let me show with an example:
Original text: This is a line.
Encoded text: (.T#*T#*%*=T50;
Now, as I said, each character represents another character, '(' is 'T', '.' is actually a 'h' and so on.
Now I could just go with
string decoded = encoded.Replace('(','T'); //T.T#*T#*%*=T50;
And that will solve one problem, but when I reach character 'T' that is actually encoded character 'i' I will have to replace all 'T' with 'i', which means that all previously decoded letter 'T's (that were once '(') will also change along with the encoded 'T'.
//T.T#*T#*%*=T50; -> i.i#*i#*%*=i50;
in this situation it's obvious that I should've just went the other way around, first change 'T' to 'i' and then '(' to 'T', but in the text I'm changing that kind of analysis is not an option.
What's the alternative here that I could do to perform the task correctly?
Thank you!
One possible solution is do not use replace string method at all.
Instead you can create method which for every encoded character will output decoded one, and then go through your string as through array of char and for every character in this array use "decryption" method to get decoded character - thus you'll receive decoded string.
For example (using StringBulder to create new string):
private static char Decode(char source)
{
if (source == '(')
return 'T';
else if (source == '.')
return 'h';
//.... and so on
}
string source = "ABC";
var builder = new StringBuilder();
foreach (var c in source)
builder.Append(Decode(c));
var result = builder.ToString();
Using .Replace() probably isn't the way to go in the first place, since as you're finding it covers the whole string every time. And once you've modified the whole string once, the encoding is lost.
Instead, loop over the string one time and replace characters individually.
Create a function that accepts a char and returns the replaced char. For simplicity, I'll just show the signature:
private char Decode(char c);
Then just loop over the string and call that function on each character. LINQ can make short work of that:
var decodedString = new string(encodedString.Select(c => Decode(c)).ToArray());
(This is freehand and untested, you may or may not need that .ToArray() for the string constructor to be happy, I'm not certain. But you get the idea.)
If it's easier to read you can also just loop manually over the string and perhaps use a StringBuilder with each successive char to build the final decoded result.
Without knowledge of your encryption algorithm, this answer assumes that it's a simple character translation akin to the Caesar Cipher.
Pass in your encrypted string, the method loops over each character, adjusting it by the value of shiftDelta and returns the resulting string.
private string Decrypt(string input)
{
const int shiftDelta = 10;
var inputChars = input.ToCharArray();
var outputChars = new char[inputChars.Length];
for (var i = 0; i < outputChars.Length; i++)
{
// Perform character translation here
outputChars[i] = (char)(inputChars[i] + shiftDelta);
}
return outputChars.ToString();
}
I need to process a numeral as a string.
My value is 0x28 and this is the ascii code for '('.
I need to assign this to a string.
The following lines do this.
char c = (char)0x28;
string s = c.ToString();
string s2 = ((char)0x28).ToString();
My usecase is a function that only accepts strings.
My call ends up looking cluttered:
someCall( ((char)0x28).ToString() );
Is there a way of simplifying this and make it more readable without writing '(' ?
The Hexnumber in the code is always paired with a Variable that contains that hex value in its name, so "translating" it would destroy that visible connection.
Edit:
A List of tuples is initialised with this where the first item has the character in its name and the second item results from a call with that character.
One of the answers below is exactly what i am looking for so i incorporated it here now.
{ existingStaticVar0x28, someCall("\u0028") }
The reader can now instinctively see the connection between item1 and item2 and is less likely to run into a trap when this gets refactored.
You can use Unicode character escape sequence in place of a hex to avoid casting:
string s2 = '\u28'.ToString();
or
someCall("\u28");
Well supposing that you have not a fixed input then you could write an extension method
namespace MyExtensions
{
public static class MyStringExtensions
{
public static string ConvertFromHex(this string hexData)
{
int c = Convert.ToInt32(hexCode, 16);
return new string(new char[] {(char)c});
}
}
}
Now you could call it in your code wjth
string hexNumber = "0x28"; // or whatever hexcode you need to convert
string result = hexNumber.ConvertFromHex();
A bit of error handling should be added to the above conversion.
I'm trying to convert some data into sql statements with the use of Streamreader and Streamwriter.
My problem is, when i split lines which in which between 2 delimiters is nothing, not even a space, they get ignored and i get a IndexOutOfRange error
because my temparray only goes till temparray[3] , but it should go to like temparray[6] ..
How can i split and use Null values or replace those null values with a simple char, so that i dont get an IndexOutOfRange error when i want to create my sql statements ?
foreach (string a in values)
{
int temp = 1;
String[] temparray = a.Split(';');
streamWriter.WriteLine("Insert into table Firma values({0},'{1}','{2}')", temp, temparray[1], temparray[4]);
temp++;
}
First of all, this is asking for trouble (SQL injection). You should at the very least escape the values parsed from the string.
And you seem to be mistaken, as String.Split does exactly what you want by default: "x;y;;z".Split(';') returns a four-element array {"x", "y", "", "z"}. You can achieve the described behavior by using StringSplitOptions.RemoveEmptyEntries: "x;y;;z".Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) returns a three-element array {"x", "y", "z"}. Which is what you do not want, as you say.
Either way, "Überarbeitung der SAV Seite;b.i.b.;;;;PB;".Split(';') returns a seven-element array here for me, so check your inputs and implementation…
If you print out your string, I'm pretty sure it will not be what you expect it to be.
static void Main(string[] args)
{
var result = "Überarbeitung der SAV Seite;b.i.b.;;;;PB;".Split(';');
foreach (var part in result)
{
Console.WriteLine(" --> " + part);
}
Console.ReadLine();
}
This works great. It will not ignore the empty values. It will print
--> Überarbeitung der SAV Seite
--> b.i.b.
-->
-->
-->
--> PB
-->
including the empty values.
Greetings to bib Paderborn :)
If you're using SQL Server, you can return empty strings instead of null by using the ISNULL operator in your query.
For example:
SELECT ISNULL(PR_Arbeitstitel, '') FROM Table
Why don't you iterate over your temparray to build up a string of param values.
This is by no means perfect, but should point you in the direction
foreach (string a in values)
{
int temp = 1;
String[] temparray = a.Split(';');
var stringBuilder = new StringBuilder();
foreach (var s in temparray)
stringBuilder.Append("'" + s + "',");
var insertStatement = string.Format("Insert into table Firma values({0}, {1})", temp, stringBuilder.ToString().TrimEnd(','));
temp++;
}
Why would you have 2 delimiters in a row with nothing inbetween them? Do you not control the input?
In that case you could control it by inserting a so-called sentinel value, such as "IGNOREMEPLEASE":
String[] temparray = a.Replace(";;", ";IGNOREMEPLEASE;").Split(';');
Then the rest of your code knows that IGNOREMEPLEASE means there was an empty line, and it should be ignored.
That being said, be very careful about what you send to a database, and scrub incoming data that you use to build SQL statements with, to get rid of anything dangerous.
I don't see your issue occurring. The following outputs a string.Empty for string[2] and has all 5 elements
string[] str = "0,1,,3,4".Split(new char[] { ',' });
foreach (string s in str)
{
Debug.Print(s);
}
output
0
1
3
4
I've tried to reproduce with your example of string "Überarbeitung der SAV Seite;b.i.b.;;;;PB;" but everything was fine. I've got 7 items in array.
You can try to use
string s = "Überarbeitung der SAV Seite;b.i.b.;;;;PB;";
var result = s.Split(new[] { ';' }, StringSplitOptions.None);
To be sure that StringSplitOptions.RemoveEmptyEntries is not enabled.
Perhaps use the ?? operator:
streamWriter.WriteLine(
"Insert into table Firma values({0},'{1}','{2}')",
temp,
temparray[1] ?? 'x',
temparray[4] ?? 'x');
This still is only safe, though, if you know for sure that your input has at least 5 tokens after splitting. If you can't guarantee this you'll need to wrap it in a conditional:
if (temparray.Length < 5)
{
// handle invalid input
}
So what I am trying to do is as follows :
example of a string is A4PC
I am trying to replace for example any occurance of "A" with "[A4]" so I would get and similar any occurance of "4" with "[A4]"
"[A4][A4]PC"
I tried doing a normal Replace on the string but found out I got
"[A[A4]]PC"
string badWordAllVariants =
restriction.Value.Replace("A", "[A4]").Replace("4", "[A4]")
since I have two A's in a row causing an issue.
So I was thinking it would be better rather than the replace on the string I need to do it on a character per character basis and then build up a string again.
Is there anyway in Linq or so to do something like this ?
You don't need any LINQ here - String.Replace works just fine:
string input = "AAPC";
string result = input.Replace("A", "[A4]"); // "[A4][A4]PC"
UPDATE: For your updated requirements I suggest to use regular expression replace
string input = "A4PC";
var result = Regex.Replace(input, "A|4", "[A4]"); // "[A4][A4]PC"
This works well for me:
string x = "AAPC";
string replace = x.Replace("A", "[A4]");
EDIT:
Based on the updated question, the issue is the second replacement. In order to replace multiple strings you will want to do this sequentially:
var original = "AAPC";
// add arbitrary room to allow for more new characters
StringBuilder resultString = new StringBuilder(original.Length + 10);
foreach (char currentChar in original.ToCharArray())
{
if (currentChar == 'A') resultString.Append("[A4]");
else if (currentChar == '4') resultString.Append("[A4]");
else resultString.Append(currentChar);
}
string result = resultString.ToString();
You can run this routine with any replacements you want to make (in this case the letters 'A' and '4' and it should work. If you would want to replace strings the code would be similar in structure but you would need to "look ahead" and probably use a for loop. Hopefully this helps!
By the way - you want to use a string builder here and not strings because strings are static which means space gets allocated every time you loop. (Not good!)
I think this should do the trick
string str = "AA4PC";
string result = Regex.Replace(str, #"(?<Before>[^A4]?)(?<Value>A|4)(?<After>[^A4]?)", (m) =>
{
string before = m.Groups["Before"].Value;
string after = m.Groups["After"].Value;
string value = m.Groups["Value"].Value;
if (before != "[" || after != "]")
{
return "[A4]";
}
return m.ToString();
});
It is going to replace A and 4 that hasn't been replaced yet for [A4].