Length of a string without using any built-in functions

code that returns the length of a string without using any built-in functions.
thanks
Sam

A string is internally represented by a character array.  An array of characters will reside on the stack, not the heap.  Yes, we always learned that String is a reference type, but what goes on in your memory might still surprise you...
A struct is internally represented by only it's private properties, sequentially on the stack.
So basically, what I thought is happening by messing with the structlayout: is only tricking our programming a bit into thinking that the top X bytes on the stack represent a chararray, while actually we put them there as a string.
Wrong. True. And wrong.
A string is internally represented by, in that order, an array length, a string length, the chars. None of them resides on the stack.
An array is internally represented by, in that order, an array length and the chars. None of them resides on the stack.
When you use the FieldOffset attribute to handle the string as a char array, you don't get anything right:
- the Length returned is the "array length" of the string, which is equal to the string length + 1.
- the chars returned by the array indexer are shifted by 2 chars (the length of the "string length" field).
You can use the FieldOffset to make that work, but it needs a little bit more work.
unsafe static int Test()
string myString = "This string may contain many string inside this string";
string testString = "string";
int countResult = 0;
fixed (char* myChars = new StringToChar { str = myString }.chr, testChar = new StringToChar { str = testString }.chr)
// The 2 first chars of the array are actually the string length.
int myCharsLength = myChars[1] << 16 | myChars[0];
int testCharLength = testChar[1] << 16 | testChar[0];
for (int i = 0; i < myCharsLength - testCharLength + 1; i++)
if (myChars[i + 2] == testChar[2])
for (int j = 1; j < testCharLength; j++)
var c = testChar[7];
if (myChars[i + 2 + j] != testChar[j + 2])
goto endOfCharAnalyses;
countResult++;
endOfCharAnalyses:
continue;
return countResult;

Similar Messages

  • Find the length of a String, without using any String API

    Hi All,
    I need to write an method which will accept String obj as an argument and will return its length, but method should not have any String API.
    Please help

    Simratpal wrote:
    Hi All,
    I need to write an method which will accept String obj as an argument and will return its length, but method should not have any String API.
    Please helpWell I have strongly argued against doing this, (it seems like a pointless exercise), and I have even stated that it cannot be done, even Reflection at some level will use a String method. I have not bothered to dissect wether the same is true with JNI. However, if we take the statement of the original problem exactly as stated, particularly the
    but method should not have any String API.i.e. we don't care if a String API is used 'under the covers', just so long as there is no direct usage in the new method that is written, then the answer is trivially easy:
    public class Main
        public static void main(String args[])
            Main worker = new Main();
            String str = "123456789";
            int len = worker.strLenUsingNoExplicitStringClassMethod(str);
            System.out.println("Length of string \""+str+"\""+" is "+len);
        public int strLenUsingNoExplicitStringClassMethod(String string)
            StringBuilder sb = new StringBuilder(string);
            return sb.length();
    }

  • Can i make a book in iPhoto without using any of the built in layout templates, which are too limiting when i have already cropped my pictures to show just what I want. Ideally I just want to drag and drop and arrange and size the pictures myself

    Can i make a book in iPhoto without using any of the built in layout templates, which are too limiting when i have already cropped my pictures to show just what I want. Ideally I just want to drag and drop and arrange and size the pictures myself

    If you have Pages you can create customs pages for your book as TD suggested. If you have Pages from iWork 09 or 11 this app will add 80 or so additional frames to those offered:  Frames and Strokes Installer. Don't use it on the latest Pages version, however.
    This tutorial shows how to create a custom page with the theme's background: iP11 - Creating a Custom Page, with the Theme's Background for an iPhoto Book.  Once the page is complete to get it into iPhoto as a jpeg file follow these steps:
    Here's how to get any file into iPhoto as a jpeg file:
    1 - open the file in any application that will open it.
    2 - type Command+P to start the print process.
    3  - click on the PDF button and select "Save PDF to iPhoto".
    NOTE:  If you don't have any of those options go to Toad's Cellar and download these two files:
    Save PDF to iPhoto 200 DPI.workflow.zip
    Save PDF to iPhoto 300 DPI.workflow.zip
    Unzip the files and place in the HD/Library/PDF Services folder and reboot.
    4 - select either of the files above (300 dip is used for photos to be included in a book that will be ordered).
    5 - in the window that comes up enter an album name or select an existing album and hit the Continue button.
    That will create a 200 or 300 dpi jpeg file of the item being printed and import it into iPhoto. For books to be printed choose 300 dpi.

  • Smooth transitions between menus without using DVDSPs built-in transitions?

    My project has two menus: a main menu and a chapter menu. When going from one menu to the other I would like to have the current menu fade out and the new menu fade in. When going from the end of the track or when using the remote menu button after getting to the track from the main menu I would like to have the main menu fade in (and the background for the chapter menu not appear). When using the remote menu button after getting to the track from the chapter menu I would like to have the chapter menu fade in (and the background for the main menu not appear).
    I am able to accomplish what I described above by using DVDSPs built-in transitions. However, I have been advised by Trai Forrester that DVDSPs built-in transitions can cause problems: http://www.dvdverification.com/public/155.cfm I have therefore modified my project to not use DVDSPs built-in transitions, but in order to have my project behave as I have described above I found it necessary to use two versions of the main menu and two versions of the chapter menu. One version of the main menu has a video file that fades in the background of the main menu, while the second version of the main menu has a video file that fades out the background of the chapter menu and then fades in the background of the main menu. (Similarly one version of the chapter menu has a video file that fades in the background of the chapter menu, while the second version of the chapter menu has a video file that fades out the background of the main menu and then fades in the background of the chapter menu.)
    My project behaves as desired using the two pairs of menu and does not use DVDSPs built-in transitions, so that pleases me. However, the almost-identical copies of the menus annoys me greatly. For an explanation of the programming principles that lead to my annoyance, see http://en.wikipedia.org/wiki/Code_duplication and http://en.wikipedia.org/wiki/Don%27trepeatyourself for elaboration.
    Is there a way to have just two menus instead of two pairs of menus and achieve what I described above without using DVDSPs built-in transitions?
    Looking forward to being surprised by a clever solution,
    John Link

    Since you have no audio or motion then try the jump to loop point script. Either way would be fine.
    I played around with that a little bit and it seems that to get all the fade-outs I'd like to have would require several scripts and keeping track of SPRM 7. I think that I am going to abandon all of the fade-outs but keep the fade-ins. I can do that with a single main menu and a single chapter menu and not use the built-in transitions or any scripts at all. The behavior looks good and I think the disc will be very safe.
    I agree, duplicating code is not good practice but remember your not writing code here - DVDSP is doing all this work under the hood for you.
    I may not be writing code but I am programming the DVD and the principle of non-duplication is violated by almost-identical menus.
    If you'd like check out a tool like My DVDEdit or AfterEdit
    http://www.mydvdedit.com/
    http://dvdafteredit.com/
    It allows you to see the "real" DVD Structure which tools like DVDSP or Encore hide to make things simple. You can even go through the abstraction layer line by line to see how that SPRM 7 is used (wish I knew why that Sony Player doesn't work for your project).
    Be sure to take a look at my report on the RDR-GX355: http://discussions.apple.com/thread.jspa?threadID=1896575&tstart=0 That player also operates incorrectly on Concert for George: http://www.amazon.com/Concert-George-Andy-Fairweather-Low/dp/B0000CEB4V/ref=pdbbs_sr1?ie=UTF8&s=music&qid=1233954620&sr=8-1
    Its not rocket science (especially for a programming like yourself) but remember authoring a disc in DVDSP vs a spec tool like Scenarist isn't even in the same ballpark - not even the same sport Last time I heard Scenarist is down to $6000 - it was $20K a couple years ago.
    That's a deal breaker! I'll be working with DVDSP in the foreseeable future.
    Also go here:
    http://www.dvd-replica.com/DVD/index.php
    it explains the spec in detail
    Thanks. I'll take a look.

  • Is it possible to retrieve photos from an iPod Touch 5th Generstion iOS 7 backup to iTunes on a MacBook, without using any other iDevice?

    Is it possible to retrieve photos from an iPod Touch 5th Generation iOS 7 backup to iTunes on a MacBook, without using any other iDevice?
    I Backed up my iPod Touch 5th Generation iOS7 onti my MacBook using iTunes
    Later, I lost the iPod.
    I want to retrieve as much of the data, especially photos, as possible ftom the backup.
    I do not have another iPod to use the restore function.
    Is there any other way to retrieve the photos or any other data from the backup?

    You could restore an iPad or iPhone from the backup.
    Some of this apps are compatible with a Mac
    How to perform iPad recovery for photos, videos
    Wondershare Dr.Fone for iOS: iPhone Data Recovery - Wondershare Official     
    http://www.amacsoft.com/ipod-data-recovery.html

  • How to create a popup window to load HTML page in AIR application without using any mx or spark?

    How to create a popup window to load HTML page in AIR application without using any mx or spark components?
    I need to load the HTML page in popup in AIR application without using any of the <mx> or <spark> components. I need to open in the application itself not in the browser.(If we use navigateToURL() it will open in th browser)

    Can we achieve this? can somebody help me on this scenario..

  • I have a macmini on order, I wonder if I can pair the wireless apple keyboard and magic touchpad without using any other input devices, especially, since everything is brand new and not yet paired.

    I have a macmini on order, I wonder if I can pair the wireless apple keyboard and magic touchpad without using any other input devices, especially, since everything is brand new and not yet paired.

    You may just want to save yourself any possible issues
    by just hooking up a wired keyboard and mouse on first
    start up.  Any USB keyboard and mouse should work.
    There have been many that have had problems on first boot
    using the Bluetooth devices. 

  • I am using Iphone 5s my battery is draining like anything. Without using any application also it seems i am using iphone 5s but in show only really i am using like previous nokia 1100 model.

    I am using Iphone 5s my battery is draining like anything. Without using any application also it seems i am using iphone 5s but in show only really i am using like previous nokia 1100 model.

    Are there apps on your phone right now? 
    I think one of your apps is causing this.
    The only way to find out is to delete them all and then add them one by one to see what app maybe causing this.
    Especially if you've gone thru 3 iphones already.
    When you restored as new - did you sync back your stuff - apps/music or did you restore from backup?

  • How to do Indepth table analysis without using any tool

    Is there anyway of indepth analysis of tables of a database without using any tool, i.e. by means of sql's, pl/sql's only.
    My database has around 800 main tables which have several other related relational tables(objects relating 2 tables on basis of OTO, OTM, MTO, MTM object relationship) and several dependent views(made from among the 800 base table only).
    Currently database is indexed, has joins and views, all in working scenario but yet do not gauranty consistent behaviour.
    My sole purpose is to analyse all main tables (around 800 of them) in my database by running scripts and prompt errors, warnings, exceptions wherever table needs indexing or change of joins(eg - from cross to inner,etc. ) or check inorder to avoid table full scan for related relational tables and dependent views.
    My databse is Oracle10g.
    Please do revert for any doubts.

    My sole purpose is to analyse all main tables (around 800 of them) in my database by running scripts and prompt errors, warnings, exceptions wherever table needs indexing or change of joins(eg - from cross to inner,etc. ) or check inorder to avoid table full scan for related relational tables and dependent views.There are no tools which can tell whether your table needs indexing or whether you need to change joins methods, by just looking at your database. At most, you can get an idea about the missing indexes in case of a parent-child relation. Everything else, falls under application tuning - which involves sql tracing, profiling etc.
    If you cannot trace individual sessions, then you are better off monitoring the database with statspack/AWR (if licensed). Generate reports at frequent intervals, look at the resource consuming SQLs and have a discussion with dev team to fix them, whenever possible.
    EM can also be used for SQL analysis.

  • Reporting Scores without Using the Built-in Quiz

    Is it possible to set up a 'quiz' in captivate, without using the built-in quiz slides?
    The quiz slides are quite restrictive and clumsy and I'd rather build them myself.
    So, say if I had a slide that had a question on it and two answer buttons, 'true' and 'false'. Is it possible to use these buttons to execute an advanced action that assigned a score that could then be reported to the LMS?
    Sorry if this is a silly question.
    Best
    M

    Maybe you never found my blog? Have several articles about custom questions and reporting of those questions.
    Report Custom Questions - part 1 - Captivate blog
    Report Custom Questions - part 2 - Captivate blog
    You can search more, using tags. There are some limitations with custom questions: no question pools, reporting partial scores and penalties are difficult/impossible if you do not use JS.  Drag&Drop is a hybrid question type that allows more customisation as well. Here are the latest articles about custom questions:
    Custom Short Answer Question - Captivate blog
    Custom Hotspot questions in Captivate 8 - Captivate blog

  • Can we demodulate the signal recieved at DAQ card without using any hardware interface(by only using labview)?

    Hi all,
    Can we demodulate the signal recieved at DAQ card without using any hardware interface(by only using labview)? if yes then how? please give brief idea.
    Regards,
    Amit

    There is probably a way to do it, but it it may be easier to use an X-series board for the job.   They support a new counter capability for count reset on a digital edge without needing to be configured in encoder position mode.  I am not sure exactly how that feature's been implemented however, so maybe it won't make things easier after all.
    The plan based on the hoped-for behavior: 
    1. Configure an X-series counter for pulse generation based on "ticks" of your clock channel.
    2. Set both initial delay and low time to the critical # of ticks.
    3. Configure for count reset on a digital edge (if possible in pulse generation mode)
    4. Configure the count reset value to be the critical # (or possibly 1 less, if possible in pulse generation mode)
    5. If you want the output to remain high indefinitely, configure the counter task to use its own output as a
    pause trigger, and pause while high.
    The way pulse generation works is to preload a # of "low time" ticks into the count register.  Then every source edge will decrement the count.  When the count reaches terminal count (0), the counter's output is toggled (or can be configured to pulse).  The register is then loaded with the # of "high time" ticks and the process continues.
    You would be perpetually interrupting the count-down process as long as you got your triggers in time.  The count would keep getting reset to the # of low counts, keep decrementing toward 0 without reaching it, and so on.  If ever you did reach 0, the output state would toggle high, then the high state would prevent subsequent clock signals from decrementing the count.
    You can conceivably do a similar thing with a 6601, but I'm pretty sure you'd need 2 counters working together to get it working.
    -Kevin P

  • Rounding to 2 decimal places WITHOUT using any formatting class

    Hello
    I'm trying to round a number (double) to 2 decimal places without using any of the formatting class like (DecimalFormat or Math.Round and BigDecimal). Is it possible to do it by just using typecast?

    OP:
    BigDecimal is not a formatting class. Math.round isn't a class at all.
    Typecasting doesn't really do that sort of thing at all (unless you count dropping fractional components when casting to an integer type).
    double holds values in binary format, so it's basically impossible to round to decimal values meaningfully.
    Chuck:
    I thought that BigDecimal supported arbitrary decimal precision, so one doesn't have to do that sort of thing....?

  • Help required to create portal without using any vendor specific API's

    Hi All,
    I am trying to develope a portal without using any vendor specific API or tool like Weblogic workshop or Vignette Wizard. I would like to know whether Sun Microsystem provides any API for developing portal. I would also appreciate if I can get few links for developing portal using java API's...
    Thanks in advance...
    Dgk

    Sure Sun provides the tools: it is called the compiler. Now all you need to do is write the code for a portal. But since there are vendor specific solutions available that could make your life a lot easier, writing one yourself is like reinventing the wheel.
    Pardon my mild sarcasm, but avoiding API's not developed by Sun is not the general idea behind the Java platform. You are encouraged to use those API's.

  • Removing Duplicate Characters in a String without using a Hashset

    I was wondering if anyone knew a way of removing duplicate characters in a string without using a Hashset.
    I want to go from
    helloworld -> helowrd

    okay, here it is
    1) use a loop, look through each character in the original string
    2) look at the new string, if this character exist, don't add it, otherwise add it.
    check out methods in java.lang.String

  • How do we Back up my music files from my phone into my computer (PC) without using any programs

    I am looking for a way to back up my Music from my iPhone into the computer (Like how the iPod Nano could) WITHOUT using any programs. Is there a way? Is it possible? If so, please help....
    thankyou
    Charlie

    Music purchased from the iTunes store can be redownloaded again for free (see.http://support.apple.com/kb/HT2519)  In other words, it's already in iCloud so there's nothing you need to upload.
    However, if you don't want to run into problems syncing with your new computer you need to copy the entire iTunes folder (not just the music folder) from your old computer to your new one using one of the methods outlined here: http://support.apple.com/kb/HT4527.

Maybe you are looking for

  • What Should i do about to move in to a house with ...

    OK so im waiting for keys for my new place that is currently with bt duno if its fiber yet  i been doing research to decide what to get , was going for sky who we currently with but the router is awfully rubbish !!!!!  bt give me option to use my 1.3

  • I can not, "pick" in Options window - Privacy panel, to change "passwords" settings

    In Options window - Privacy panel, if I pick them, nothing execute, I need see my passwords . Thank you

  • NCS - Disk volume 'optvol' more than 50% used.

    Hi, I recently installed NCS and have received a major alert stating the following: "NCS disk volume 'optvol' is above the recommended disk usage, more than '50'% used" The VM was created from the NCS OVA file and I only have one 2500 controller in N

  • How do i put my music in iCloud?

    I see no way to put my 4000 plus songs in the Cloud. So far, I'm sticking with Amazon's Cloud. Much more intuitive-and-easy to use. Plus ALL my music is stored FREE (over 20 GB). Apple has lost me here, unless I can easily upload my music. I only see

  • Work flows PPTS

    Hi; can anyone kindly send me PPTS for workflows. Thanks in advernce.