Showing posts with label characters. Show all posts
Showing posts with label characters. Show all posts

Saturday, March 31, 2012

string to byte array conversion

I've a string similiar to "A509DE5B" (Length == 8 ) where each 2 characters are 1 hex number. How to convert such string into array of bytes (Lenght == 4)? In C# please, it's important...Byte.Parse()?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystembyteclassparsetopic.asp
Hi LesioS!

I think you should try out something like this (I haven't tested it out myself, not sure if it works!!)


string sBytes = "A509DE5B";

Byte[] bytes = new Byte[(int)(sBytes.Length/2)];

int i = 0, j = 0;

while(i < sBytes.Length)
{
bytes[j] = Byte.Parse(str.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}

Maybe it would work..

Good luck!
Oh, sorry, there's lots of mistakes in the code earlier code.

I tested this, and it worked, so be my guest! :)


string sBytes = "A509DE5B";
int i=0, j=0;
Byte[] bytes = new Byte[(int)(sBytes.Length/2)];
while(i < str.Length)
{
bytes[j] = Byte.Parse(sBytes.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}


byte[] bytes = new byte[str.Length / 2];
for(int i = 0; i < str.Length / 2; i++)
bytes [i] = Byte.Parse(str.Substring(i * 2, 2), NumberStyles.HexNumber);

works fine... THX

But I wonder why there's no such function like ToCharArray for string object which produces byte array. In many cases functions from .NET Framework uses byte arrays, not char arrays :(

Try this:

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

Good luck!

Newbie


I have tried this

System.Text.

ASCIIEncoding encoding =new System.Text.ASCIIEncoding();string queryStringKey =ConfigurationManager.AppSettings["queryStringKey"];byte[] key = encoding.GetBytes(queryStringKey);return key;

to achieve this

//byte[] Key = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6 };

but it is not working. What am I not getting? Newbie

Wednesday, March 28, 2012

String.Formatting a javascript code sample, how do I escape the { } characters?

Hi,

I'm trying to String.format a piece of javascript code

string.Format("function showalert(msg) { window.status = '{0}'; alert(msg); }", "Test");

This compiles ok but when it runs it has a Input string was not in a correct format exception as the '{' and '}' characters are reserved and used for substitution in the string.Format function.

Is there a way I can escape the '{}' characters so that the string.format function ignores them?

I've tried

string.Format("function showalert(msg) \{ window.status = '{0}'; alert(msg); \}", "Test");

which is normally how you escape but it dosen't work.

Thanks for your help

Auschucky

Hi ,To specify a single literal brace character informat, specify two leading or trailing brace characters; that is, "{{" or "}}".
string test =string.Format("function showalert(msg) {{ window.status = '{0}'; alert(msg); }}","Test");
Hope this helps , Gook Luck^_^
Ta, worked a treat

Monday, March 26, 2012

stringbuilder & javascript (escape characters for quotes?)

Hey,

Im trying to write a javascript array from .net. The values of the array will sometimes have single quotes in - therefore I need some way to process the quotes so that I can output the javascript in the correct way.

I have:


sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString() +"','"+ dr[1].ToString()+"','"+ dr[2].ToString() +"');\n");

However, this does not deal with the quotes. I tried:


sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString().Replace("'","\'") +"','"+ dr[1].ToString().Replace("'","\'") +"','"+ dr[2].ToString().Replace("'","\'") +"');\n");

This was to try and replace all single quotes with \' which is the javascript escape character.
However, the double quotes dont work because .net think I'm adding more code.

kind of like in original asp when you have to have multiple quotes to get in a single quote...you know what I mean :)

any help much appreciated,

PeteThe first code sample should do fine.. single quote isnt going to trip anything up. If you were wanting to use double quotes in your string-builder for javascript, you would have to escape them with \" .

Now, are you anticipating a single quote will be in your datareader columns that you are building the stringbuilder with? If so, replacethose values with \' instead of the whole stringbuilder.
Cheers Sharbel,

Trying that today.

Pete
Hold on :)

I am anticipating single quotes in the data columns. Example: " today it's the first day ... " etc etc.

I've tried putting the dataReader columns into strings then replacing single quotes with \' but that doesnt seem to work...

Pete
Hey,

completely by chance I found that backslash is an escape character for .net as well as javascript:

hence:


dr[4].ToString().Replace("'","\\'")

works fine

Cheers,

Pete
Hi Pete,

FYI, the slash isn't a ".NET" escape character, per se; it works in C# because C# shares a lot of common syntax with Javascript (and Java, and C++, and any other languages that descended from C in one form or another).

In VB.NET, you escape double quotes by repeating them, just like in old "Classic" ASP with VBScript (although if you used JScript for Classic ASP, you *would* need to use the slash to escape characters).

Cheers,

Saturday, March 24, 2012

Strip characters from string

Hi, I want the user to be able to enter any form of number in my price textbox and I will automatically strip anything that is not an integer.

I obviously can't mand a string.replace for every character, so is there a way to use a regexp to say anything that isnt 0-9?

Thanks, Davehello, u can add a validation control to the textbox with the following:

[0-9]+

this way, they can enter any number they want.
But I don't want to have to restrict it like that. Many people will enter different formats for a price. I want them to be able to use '$' or ',' or whatever and have it stripped on the backend.

I am looking at regex.replace, but I can't get it to work yet.
well,
maybe u can allow them to enter any number or character and the loop through an array of all alphabets and eleminate all not needed characters !!!
I can offer you a commercial solution. My productProfessional Validation And More includes IntegerTextBox, CurrencyTextBox, and DecimalTextBox fields. They handle the filtering of illegal keystrokes, reformatting as the user exits the field, and supply you with the actual numeric value (an integer or Double property) on the server side.

strip non-numeric characters

Is there simple way to take a string that should be all numeric (like a
credit card number) and strip out anything that isn't a digit? In the past
I've done this in VFP using the IsDigit() function, looping through each
character. It was a little awkward, but worked. Is there something similar,
or better for vb.net?

Thanks!

MattThe IsNumeric function should fill the bill...

Dim MyVar As Object
Dim MyCheck As Boolean
' ...
MyVar = "53" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "459.95" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "45 Help" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns False.

Regards,
January Smith

"MattB" <somedudeus@.yahoo.com> wrote in message
news:2hmemqFen4c9U1@.uni-berlin.de...
> Is there simple way to take a string that should be all numeric (like a
> credit card number) and strip out anything that isn't a digit? In the past
> I've done this in VFP using the IsDigit() function, looping through each
> character. It was a little awkward, but worked. Is there something
similar,
> or better for vb.net?
> Thanks!
> Matt
I would try Regex. You can look for \d and pull all instances, then concat
back the resulting array. There are a couple of other ways to work with
this.

Note that VB.NET still has IsNumber() or IsNumeric() [forget which one], so
you can still loop and test, if you want to go with VB.NET.

Another option is convert to a char array and test the numeric value of each
char. The ASCII value for numbers is extremely predictable.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

************************************************
Think Outside the Box!
************************************************
"MattB" <somedudeus@.yahoo.com> wrote in message
news:2hmemqFen4c9U1@.uni-berlin.de...
> Is there simple way to take a string that should be all numeric (like a
> credit card number) and strip out anything that isn't a digit? In the past
> I've done this in VFP using the IsDigit() function, looping through each
> character. It was a little awkward, but worked. Is there something
similar,
> or better for vb.net?
> Thanks!
> Matt
You can use the Regex.Replace method to check for any characters (\w) and replace them with an empty string. The result that would come out is a string that is all numeric.

strip non-numeric characters

Is there simple way to take a string that should be all numeric (like a
credit card number) and strip out anything that isn't a digit? In the past
I've done this in VFP using the IsDigit() function, looping through each
character. It was a little awkward, but worked. Is there something similar,
or better for vb.net?
Thanks!
MattThe IsNumeric function should fill the bill...
Dim MyVar As Object
Dim MyCheck As Boolean
' ...
MyVar = "53" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "459.95" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "45 Help" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns False.
Regards,
January Smith
"MattB" <somedudeus@.yahoo.com> wrote in message
news:2hmemqFen4c9U1@.uni-berlin.de...
> Is there simple way to take a string that should be all numeric (like a
> credit card number) and strip out anything that isn't a digit? In the past
> I've done this in VFP using the IsDigit() function, looping through each
> character. It was a little awkward, but worked. Is there something
similar,
> or better for vb.net?
> Thanks!
> Matt
>
I would try Regex. You can look for \d and pull all instances, then concat
back the resulting array. There are a couple of other ways to work with
this.
Note that VB.NET still has IsNumber() or IsNumeric() [forget which one],
so
you can still loop and test, if you want to go with VB.NET.
Another option is convert to a char array and test the numeric value of each
char. The ASCII value for numbers is extremely predictable.
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
****************************************
********
Think Outside the Box!
****************************************
********
"MattB" <somedudeus@.yahoo.com> wrote in message
news:2hmemqFen4c9U1@.uni-berlin.de...
> Is there simple way to take a string that should be all numeric (like a
> credit card number) and strip out anything that isn't a digit? In the past
> I've done this in VFP using the IsDigit() function, looping through each
> character. It was a little awkward, but worked. Is there something
similar,
> or better for vb.net?
> Thanks!
> Matt
>
You can use the Regex.Replace method to check for any characters (\w) and re
place them with an empty string. The result that would come out is a string
that is all numeric.

striping text of special characters before displaying on webpage

I have this project I am working and I have two tasks

I have a text form that takes in a users input and it is supposed to be
stored in a database and can be viewed from a webpage. I want to be
able to display the text with html special characters like "<", ">" (if
the user typed them in) without it being confused for html code and...

I want to be able to replace a newline character with a "/r/n" whenever
it is used in the text.Hi ebade2000,

String.Replace and Server.HtmlEncode should do the trick.

string s = "<display \r\n me>";
s = Server.HtmlEncode(s); // converts < etc
s = s.Replace("\r\n", "<br>"); // replaces string breaks withhtml
breaks
Response.Write(s);

On Tue, 12 Sep 2006 02:08:12 +0200, <ebade2000@.gmail.comwrote:

Quote:

Originally Posted by

I have this project I am working and I have two tasks
>
I have a text form that takes in a users input and it is supposed to be
stored in a database and can be viewed from a webpage. I want to be
able to display the text with html special characters like "<", ">" (if
the user typed them in) without it being confused for html code and...
>
I want to be able to replace a newline character with a "/r/n" whenever
it is used in the text.
>


--
Happy Coding!
Morten Wennevik [C# MVP]
Thanks that helps a whole lot.

Bade

Morten Wennevik wrote:

Quote:

Originally Posted by

Hi ebade2000,
>
String.Replace and Server.HtmlEncode should do the trick.
>
string s = "<display \r\n me>";
s = Server.HtmlEncode(s); // converts < etc
s = s.Replace("\r\n", "<br>"); // replaces string breaks with html
breaks
Response.Write(s);
>
>
>
On Tue, 12 Sep 2006 02:08:12 +0200, <ebade2000@.gmail.comwrote:
>

Quote:

Originally Posted by

I have this project I am working and I have two tasks

I have a text form that takes in a users input and it is supposed to be
stored in a database and can be viewed from a webpage. I want to be
able to display the text with html special characters like "<", ">" (if
the user typed them in) without it being confused for html code and...

I want to be able to replace a newline character with a "/r/n" whenever
it is used in the text.


>
>
>
--
Happy Coding!
Morten Wennevik [C# MVP]

Stripping characters...

I'm trying to strip the characters from a text box...
but I only know how to apply it to text...
for example..

string fname = @dotnet.itags.org."*\John Doe";
string pattern = @dotnet.itags.org."^.*\\";
string name = Regex.Replace(fname, pattern," ");

but how can i do it for a passed variable...
like @dotnet.itags.org.Request.Form["fname"];

string fname = @dotnet.itags.org.Request.Form["fname"];
string pattern = @dotnet.itags.org."^.*\\";
string name = Regex.Replace(fname, pattern," ");

--
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.comHave you tried

string pattern = @."^.*\\";
string name = Regex.Replace(Request.Form["fname"], pattern," ");

--
Regards

John Timney
Microsoft MVP

"VJ" <vncntj@.hotmail.com> wrote in message
news:%23jugUr6GGHA.532@.TK2MSFTNGP15.phx.gbl...
> I'm trying to strip the characters from a text box...
> but I only know how to apply it to text...
> for example..
>
> string fname = @."*\John Doe";
> string pattern = @."^.*\\";
> string name = Regex.Replace(fname, pattern," ");
>
> but how can i do it for a passed variable...
> like @.Request.Form["fname"];
> string fname = @.Request.Form["fname"];
> string pattern = @."^.*\\";
> string name = Regex.Replace(fname, pattern," ");
> --
> Sent via .NET Newsgroups
> http://www.dotnetnewsgroups.com

Stripping characters...

I'm trying to strip the characters from a text box...
but I only know how to apply it to text...
for example..
string fname = @dotnet.itags.org."*\John Doe";
string pattern = @dotnet.itags.org."^.*\\";
string name = Regex.Replace(fname, pattern," ");
but how can i do it for a passed variable...
like @dotnet.itags.org.Request.Form["fname"];
string fname = @dotnet.itags.org.Request.Form["fname"];
string pattern = @dotnet.itags.org."^.*\\";
string name = Regex.Replace(fname, pattern," ");
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.comHave you tried
string pattern = @."^.*\\";
string name = Regex.Replace(Request.Form["fname"], pattern," ");
Regards
John Timney
Microsoft MVP
"VJ" <vncntj@.hotmail.com> wrote in message
news:%23jugUr6GGHA.532@.TK2MSFTNGP15.phx.gbl...
> I'm trying to strip the characters from a text box...
> but I only know how to apply it to text...
> for example..
>
> string fname = @."*\John Doe";
> string pattern = @."^.*\\";
> string name = Regex.Replace(fname, pattern," ");
>
> but how can i do it for a passed variable...
> like @.Request.Form["fname"];
> string fname = @.Request.Form["fname"];
> string pattern = @."^.*\\";
> string name = Regex.Replace(fname, pattern," ");
> --
> Sent via .NET Newsgroups
> http://www.dotnetnewsgroups.com

Stripping out unwanted characters

How can I strip out unwanted characters in a string before updating the
database? For instance, in names & addresses in our client table, we want
only letters and numbers, no punctuation. Is there a way to do this?HI,

Use regular expression to remove unwanted characters and then send the
string to database. Here is a sample code to remove non-alphanumerical
characters from a string.

hoep this will help you...

public static void Main()

{

/*Reg expression to find non-alphanumeric characters*/

string pattern = @."[^A-Za-z0-9]";

/*include System.Text.RegularExpressions name space*/

Regex rgx = new Regex(pattern);

string inputStr = "ab$!Cd&%$gf!";

/*Replace non-alphanumeric characters with space*/

string outputStr = rgx.Replace(inputStr, " ");

Console.WriteLine("Output string:"+ outputStr);

}

Cheers
Vinu

"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?
Function StripUnwantedChars(ByVal StringToStrip AsString) AsString
Dim stripped AsString
If StringToStrip <> "" Then
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)
Return stripped
Else
Return ""
EndIf
EndFunction

Note : insert all the characters you want to strip inside the quotes.

For example, instead of :
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)

use :
stripped = Regex.Replace(StringToStrip, "<!#(.|\n)+?>", String.Empty)

Juan T. Llibre, asp.net MVP
aspnetfaq.com : http://www.aspnetfaq.com/
asp.net faq : http://asp.net.do/faq/
foros de asp.net, en espaol : http://asp.net.do/foros/
===================================
"et" <eagletender2001@.yahoo.com> wrote in message news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the database? For instance,
> in names & addresses in our client table, we want only letters and numbers, no punctuation. Is
> there a way to do this?
Thanks, everyone, that's exactly what I was looking for.

"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?

Stripping out unwanted characters

How can I strip out unwanted characters in a string before updating the
database? For instance, in names & addresses in our client table, we want
only letters and numbers, no punctuation. Is there a way to do this?HI,
Use regular expression to remove unwanted characters and then send the
string to database. Here is a sample code to remove non-alphanumerical
characters from a string.
hoep this will help you...
public static void Main()
{
/*Reg expression to find non-alphanumeric characters*/
string pattern = @."[^A-Za-z0-9]";
/*include System.Text.RegularExpressions name space*/
Regex rgx = new Regex(pattern);
string inputStr = "ab$!Cd&%$gf!";
/*Replace non-alphanumeric characters with space*/
string outputStr = rgx.Replace(inputStr, " ");
Console.WriteLine("Output string:"+ outputStr);
}
Cheers
Vinu
"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?
>
Function StripUnwantedChars(ByVal StringToStrip AsString) AsString
Dim stripped AsString
If StringToStrip <> "" Then
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)
Return stripped
Else
Return ""
EndIf
EndFunction
Note : insert all the characters you want to strip inside the quotes.
For example, instead of :
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)
use :
stripped = Regex.Replace(StringToStrip, "<!#(.|\n)+?>", String.Empty)
Juan T. Llibre, asp.net MVP
aspnetfaq.com : http://www.aspnetfaq.com/
asp.net faq : http://asp.net.do/faq/
foros de asp.net, en espaol : http://asp.net.do/foros/
===================================
"et" <eagletender2001@.yahoo.com> wrote in message news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl
..
> How can I strip out unwanted characters in a string before updating the da
tabase? For instance,
> in names & addresses in our client table, we want only letters and numbers
, no punctuation. Is
> there a way to do this?
>
Thanks, everyone, that's exactly what I was looking for.
"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?
>

Stripping text files

Hi all,

I'm trying to have my ASP.NET application read in a text file, and put the characters into a string.

I realized that there are some weird symbols (a square) between the texts - I think it's either a carriage return or a newline character, and want to take them out by the Trim method.

Does anybody know how I can remove those symbols? Thanks!You can use this overload

public string Trim(params char[]);
, if you know which characters you want to remove.
Most likley candidates are chr(10) (carriage return) followed by chr(13) line feed, especiallly if you are working with report files or anything unix based.

Regards

Jeff............

Strnge characters causing compilation error

hi,

i am hoping that someone may be able to help me... i have been writing
vb.net pages using visual web developer. they all work fine locally
however when i upload to the server i get the following error:

Compiler Error Message: BC30037: Character is not valid.

it looks as if some strange characters have been added to the end of
every line of code causing the script to error. see the page here:
http://www.albamclothing.com/register.aspx
doe anyone know what may cause this? or even better how to get rid of
them?

many thanksIt may be the strange return character that word puts in, Ive only seen this
when moving from a windows environment to a unix environment before, but if
there is some sort of FTP going on when youre uploading I'd suggest putting
the FTP client in BINARY mode before uploading...

Regards

Rod
<tom_burrow@.umbro.co.ukwrote in message
news:1158137142.668189.67720@.e63g2000cwd.googlegro ups.com...

Quote:

Originally Posted by

hi,
>
i am hoping that someone may be able to help me... i have been writing
vb.net pages using visual web developer. they all work fine locally
however when i upload to the server i get the following error:
>
Compiler Error Message: BC30037: Character is not valid.
>
it looks as if some strange characters have been added to the end of
every line of code causing the script to error. see the page here:
http://www.albamclothing.com/register.aspx
>
doe anyone know what may cause this? or even better how to get rid of
them?
>
many thanks
>