Showing posts with label character. Show all posts
Showing posts with label character. Show all posts

Saturday, March 31, 2012

String to convert into Double

Hello All,

I am having string object coming from a DataSet. It can contain either the Numeric Strings (like "123","123.23",...) or even the Character string (Like "America","Britain"...).

Now, I am assigning this value to another column in the dataset whose datatype is Doube. Now, I wanted to check before assigning whether whatever the String I am getting from the Source column can it be converted to Double or not?

i.e I want to know is there any object/method in .Net Framework using which I can know whether I can convert one datatype to another datatype or not?

Any help regarding this would be great.

Thanks in Advance,
Areef.Hi Areef,
I am not familiar with such an object, but you can use Double.TryParse to perform your task.
Hi pmd_areef,

Try the following for testing if value is a Double. Example:


[C#]
/// <summary>
/// Is the value supplied numeric (Integer, Double).
/// </summary>
/// <param name="number">Value to test</param>
/// <returns></returns>
public bool IsNumeric(object number)
{
double tempResult;
return IsNumeric(number, out tempResult);
}

public bool IsNumeric(object number, out double result)
{
return Double.TryParse(number.ToString(), System.Globalization.NumberStyles.Any,
System.Globalization.NumberFormatInfo.InvariantInfo, out result);
}


Hope this helps.

Monday, March 26, 2012

String.Split with multi character delimiter

The Split method of the String class takes an array of char as it's
parameter. Rather than declaring a String, you need to declare a char array,
and work with that. Example:

Dim delString As String = "#|#"
Dim del As Char() = delString.ToCharArray()

...

s = source.Split(del)

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"PCK" <anonymous@dotnet.itags.org.discussions.microsoft.com> wrote in message
news:3CCCD026-B1BB-4F2D-8DE2-7D3BD398127F@dotnet.itags.org.microsoft.com...
> Hi,
> I have a string that I would like split into a single dimension string
array. The source string has a multi character delimiter. It appears that
string.split(delimiter) only splits based on the first character of the
delimiter.
> For example:
> Dim s() As String
> Dim source As String
> Dim del As String
> del = "#!#"
> source = "ABC#!#DEF#!#GHI"
> s = source.Split(del)
> s(0) = "ABC"
> s(1) = "!"
> s(2) = "DEF"
> s(3) = "!"
> s(4) = "GHI"
> Where as I would like the following returned. Does anyone know of a built
in function to do this?
> s(0) = "ABC"
> s(1) = "DEF"
> s(2) = "GHI"
> Thanks.
> PCKKevin, thanks for the response

I had thought about that earlier. Actually what happens when you use a char array is that it splits based on any item in the array not on the concatenation of all items in the array

Do you have any other suggestions.
myString.Replace( "#!#", "!" ).Split ( "!" ); ?

Dan.

"PCK" <anonymous@.discussions.microsoft.com> wrote in message
news:3F0E32B3-4C65-4AA2-A1A2-110F0644FA6A@.microsoft.com...
Kevin, thanks for the response.

I had thought about that earlier. Actually what happens when you use a char
array is that it splits based on any item in the array not on the
concatenation of all items in the array.

Do you have any other suggestions.
> I had thought about that earlier. Actually what happens when you use a
char array is that it splits based on any item in the array not on the
concatenation of all items in the array.

Oops. Sorry. That's true. Well, you could always use the Visual Basic.Net
Split() method (function), which takes a string as an argument.
Alternatively, you could try Daniel's solution.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"PCK" <anonymous@.discussions.microsoft.com> wrote in message
news:3F0E32B3-4C65-4AA2-A1A2-110F0644FA6A@.microsoft.com...
> Kevin, thanks for the response.
> I had thought about that earlier. Actually what happens when you use a
char array is that it splits based on any item in the array not on the
concatenation of all items in the array.
> Do you have any other suggestions.
the problem is the split method is not intended for use with string
seperators, to do one that works properly, you'd have to write one yourself.

alternatively, if there is a character you know (think highly likely) will
NOT appear in your text, use the replace method to convert to that character
as a seperator, then split.

hope that helps.
Dan.

"PCK" <anonymous@.discussions.microsoft.com> wrote in message
news:A6A5A7D8-5BB1-46D7-BC35-ABD8DD55130E@.microsoft.com...
Dan, thanks for the response.

But what if the data was "ABC#!#D!EF#!#GHI"

That would split it out as

ABC
D
EF
GHI

versus

ABC
D!EF
GHI
The VB Split method is what I was looking for. Thanks for the help.

Stringbuilder Parsing Text: Need to remove square character

Hi everyone,

I am attempting to parse data from a webpage and want to remove any unneccesary junk from the string. I start by removing any Tags from the text I have retrieved from the web page. Next, I split the text into an array. However, I end up with a string that contains a bunch of characters that look like ?, sometimes there are many in a row: ???? in each string. I would like to remove these characters.

These characters are the only things left separating me from the data I want, but I am not sure how to remove them... Does anyone have an idea? It is interesting that when I display my string in a textbox, or using a label, the squares are not visible (I think they display as spaces) but when I debug I see them.

Thanks,

zoop

Those chars probably are line feeds, tabs or some other control chars.

Try:

Dim junk asString ="bla bla bla....."

junk=junk.replace(ControlChars.Lf,"")

junk=junk.replace(ControlChars.NewLine,"")

junk=junk.replace(ControlChars.Tab,"")


etc, etc...


If I'm not mistaken you are seeing the hidden space place holder. You can use regular expressions to remove them. Try something like below to remove them.

using System.Text.RegularExpressions;

private string StripSpaces(string inputString)
{
return Regex.Replace(inputString, @."[^\s$]","");
}


Thanks for the input fellas. I have tried the suggestions above along with some variations and came up short. Replacing the ControlChars does not seem to make a difference on the format of the string. Running the stripSpaces function removes all of the data I am interested in and returns only the chars I am attempting to remove (blanks, or squares). Perhaps I lost something when I translated it into VB...

Anyway, since there is not much code to go over I thought perhaps it would help if I posted what I have here. I am going to omit the section where I replace any ControlChars for brevity, as it does not seem to make a difference.

1Private Sub btnSubmit_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles btnSubmit.Click2'// Store Page Source in DOC3Dim reqAs WebRequest = WebRequest.Create("http://world5.knightfight.co.uk/index.php?ac=highscore&vid=0")4Dim respAs WebResponse = req.GetResponse56Dim sAs Stream = resp.GetResponseStream7Dim srAs StreamReader =New StreamReader(s, Encoding.ASCII)8Dim docAs String = sr.ReadToEnd910'// Format text in DOC using StringBuilder Class11Dim sbAs StringBuilder =New StringBuilder(doc)12Dim endIndexAs Integer = sb.ToString.IndexOf("showuserid=")13Dim newString()As String14Dim strTestAs String1516'// Remove Unwanted Text17strTest = sb.Remove(0, endIndex).ToString1819'// Remove HTML Tags and Spaces20strTest = StripTags(strTest)21strTest = stripSpaces(strTest)2223'// TEMP - Display Preview in Multiline Textbox24txtbWebData.Text = strTest2526'// Split String into Array27newString = Split(strTest," ")28End Sub2930Public Function StripTags(ByVal HTMLAs String)As String31' Removes tags from passed HTML32Dim objRegExAs _33System.Text.RegularExpressions.Regex34Return objRegEx.Replace(HTML,"<[^>]*>","*")35End Function3637Public Function stripSpaces(ByVal inputStringAs String)As String38Dim objRegExAs _39System.Text.RegularExpressions.Regex40Return objRegEx.Replace(inputString,"[^\s$]","")41End Function42

I thought it would be an interesting exercise to try and capture some data from a highscores list on a website. The URL is in the code above, http://world5.knightfight.co.uk/index.php?ac=highscore&vid=0,so you could reproduce my results if you like. The end goal is to capture the data in the highscores list and format it in a way that makes sense. If you think there is a better approach please let me know :).

Thanks,

zoop


Sorry about that. Replace Return objRegEx.Replace(inputString, "[^\s$]", "") with Return objRegEx.Replace(inputString, "[^\S$]", ""). The \s matches any white space character and the \S matches any non-white space character.

Thursday, March 22, 2012

Structures, character arrays, and unmanaged code in C#

I'm not entirely sure how to ask this question because, frankly, I have no idea what I'm dealing with. I have a C header file that would allow me to access an API. The header needs to be converted to .NET so I can use the API. I converted and tested the methods successfully (using DllImport). I'm running into a problem converting, well using, a structure:
struct record {
char id[32];
char name[64];
char number[16];
char dept[64];
... you get the idea ...
};

My searches have brought me to the conclusion that I'm working with something called "unmanaged code", which I gather means the CLR won't be touching my API. I converted the struct to something that I think is equivalent:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct pager_record
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string id;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string number;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string dept;
... you get the idea ...
};

When I try to pass the structure into my API call, I get an "Object Reference not set to an instance of an object" error. This is the code I use to initialize and populate the struct:


private void btnAdd_Click(object sender, System.EventArgs e)
{
StringBuilder error = new StringBuilder(Export.ERROR_BUFFER_SIZE);
Admin.record pr = new Admin.record();

pr.id = "123456789";
pr.name = "George Bush";
pr.number = "5555555555";
pr.dept = "Executive";
... you get the picture ...

This is the line that fails:


int Stat = Admin.pagemate_add(pr, error);

And this is the API method itself:
[DllImport(API.dll)]
public static extern int add(record Record, StringBuilder error_buffer);

I know that I'm populating the struct fine; if I change the struct to a managed equivalent (without the [MarshalAs(��) ] code, data makes it into program. It's just that the data that gets in is gibberish. I'm guessing this has something to do with references, since .NET passes data ByVal by default.

So the questions:
1.Is this how I want to rewrite the Struct?
a.Why?
2.What do I need to do to pass the structure into the API call?
a.Why?

Thanks��

-ChrisChris,

Unmanaged simply means that the CLR won't do type-checking and garbage collection for your non .Net library.

What level of indirection does your unmanged method require? This may affect how you can pass the struct into the API. If you need one level of indirection you can pass the struct in using the ref keyword. No indierction, you can use standard byval. Two levels, you are out of luck. See this MSDN article for more information on supported indirection levels.

Also, I think the attribute you need on your struct members is [FieldOffset] vs [MarshallAs].

What you are really dealing with here is called Platform Invoke, or P-Invoke.

Hope this helps.

-kristopher
Kristopher,

Thanks. I'm not sure but I think I require one level of indirection. Here's the original method definition:

extern long int add(struct record *, char *);

Changing to [FieldOffset] and passing the struct byref allows the code to execute again. Interesting results. I call the API through a button.click event. The first time I press the button (or call the API) it tells me the record ID is empty or null, and the insert fails. If I click a second time it will addsomething, but not what I put in the fields. A third call fails the same way the first does, a fourth tries to add (but fails because the record already exists), etc.

-Chris
Interesting. Have you verified that what is being passed to the API is the same as what you entered (i.e. by using the debugger)? Also, check to make sure that your offsets are correct, otherwise its possible you're stepping on other struct members (aka a C union).

-k