Reverse Strings using rercursion and iteration

Hi,
I really need some help, am quite new to java and am struggling.
I want to design 2 methods, both 2 reverse strings.
1) uses StringBuffer and iteration
2) uses Strings and recursion
I would be greatful for any advice or help.
Thanx xxxxx Nats xxxxxx

Oh, you need to do it using both methods.... Sorry, didn't realise it was coursework :)
Using StringBuffer and iteration
public StringBuffer reverse(StringBuffer buff) {
    int halfLen = buff.length();
    int len = buff.length();
    for(int i=0; i < halfLen; i++) {
         char c1 = buff.getCharAt(i);
         char c2 = buff.getCharAt((len - i) - 1);
         buff = buff.setCharAt(i, c2);
         buff = buff.setCharAt((len - i) - 1, c1);
    return buff;
}And for String using recursion
public String reverse(String str) {
    char[] chars = new char[str.length];
    str.getChars(0, chars, 0, str.length());
    reverseChars(chars, 0, str.length() / 2);
    return new String(chars);  
private reverseChars(char[] chars, int index, int halfLen) {
    //* end condition
    if(index >= halfLen) return;
    topIndex = (chars.length - 1) - index;
    char tmp = chars[index];
    chars[index] = chars[topIndex];
    chars[topIndex] = tmp;
    reverseChars(chars, ++index, halfLen);
}I only wrote this code on the fly so things may break but it is a start.

Similar Messages

  • How to pick max value from a column of a table using cursor and iteration

    Hello Everybody
    I have a table loan_detail
    and a column in it loan_amount
    now i want to pick values from this table using cursor and then by using iteration i want to pick max value from it using that cursor
    here is my table
    LOAN_AMOUNT
    100
    200
    300
    400
    500
    5600
    700i was able to do it using simple loop concepts but when i was trying to do this by using cursor i was not able to do it .
    Regards
    Peeyush

    SQL> SELECT MAX(sal) Highest_Sal,MIN(sal) Lowest_Sal FROM emp;
    HIGHEST_SAL LOWEST_SAL
           5000        800
    SQL> set serverout on
    SQL> DECLARE
      2    TYPE tmp_tbl IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
      3    sal_tbl tmp_tbl;
      4    CURSOR emp_sal IS
      5      SELECT sal FROM emp;
      6    counter INTEGER := 1;
      7  BEGIN
      8    FOR i IN emp_sal LOOP
      9      sal_tbl(i.sal) := counter;
    10      counter := counter + 1;
    11    END LOOP;
    12    DBMS_OUTPUT.put_line('Lowest SAL:' || sal_tbl.FIRST);
    13    DBMS_OUTPUT.put_line('Highest SAL:' || sal_tbl.LAST);
    14  END;
    15  /
    Lowest SAL:800
    Highest SAL:5000
    PL/SQL procedure successfully completed.
    SQL> Even smaller
    SQL> DECLARE
      2    TYPE tmp_tbl IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
      3    sal_tbl tmp_tbl;
      4    CURSOR emp_sal IS
      5      SELECT sal FROM emp;
      6    counter INTEGER := 1;
      7  BEGIN
      8    FOR i IN emp_sal LOOP
      9      sal_tbl(i.sal) := 1;
    10    END LOOP;
    11    DBMS_OUTPUT.put_line('Lowest SAL:' || sal_tbl.FIRST);
    12    DBMS_OUTPUT.put_line('Highest SAL:' || sal_tbl.LAST);
    13  END;
    14  /
    Lowest SAL:800
    Highest SAL:5000
    PL/SQL procedure successfully completed.
    SQL> Edited by: Saubhik on Jan 5, 2011 4:41 PM

  • How to Split the string using Substr and instr using loop condition

    Hi every body,
    I have below requirement.
    I need to split the string and append with single quotes('') followed by , (comma) and reassign entire values into another variable. so that i can use it where clause of update statement
    for example I am reciveing value as follows
    ALN varchar2(2000):=(12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434);
    Note: In the above variable i see 8 transactions, where as in real scenario i donot how many transaction i may recive.
    after modification i need above transactions should in below format
    ALTR Varchar2(2000):=('12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434');
    kindly help how to use substr and instr in normal loop or for loop or while loop while modifying the above transactions.
    Please help me to sort out this issue.
    Many Thanks.
    Edited by: user627525 on Dec 15, 2011 11:49 AM

    Try this - may not be the best way but...:
    create or replace type myTableType as table of varchar2(255)
    declare
    v_array mytabletype;
    v_new_str varchar2(4000);
    function str2tbl
             (p_str   in varchar2,
              p_delim in varchar2 default '.')
             return      myTableType
        as
            l_str        long default p_str || p_delim;
             l_n        number;
             l_data     myTableType := myTabletype();
        begin
            loop
                l_n := instr( l_str, p_delim );
                exit when (nvl(l_n,0) = 0);
                l_data.extend;
                l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
                l_str := substr( l_str, l_n+length(p_delim) );
            end loop;
            return l_data;
       end;
    begin
      v_array := str2tbl ('12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434', ',');
          FOR i IN 1 .. v_array.COUNT LOOP
             v_new_str := v_new_str || ''''||v_array(i)||'''' || ',';
          END LOOP;
       dbms_output.put_line(RTRIM(v_new_str, ','));
    end;  
    OUTPUT:
    =======
    '12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434'HTH
    Edited by: user130038 on Dec 15, 2011 12:11 PM

  • Enterprise portal access using reverse proxy using Apache and webdispatcher

    Hi Guys,
    As requirement, we need to give solution to customer about Reverse proxy scenario. I am new to this part.
    What we have think of to use Apache and Web dispatcher.
    I tried to search documents and found some sdn links also but still i am not comfortable to go about.
    Need suggestion and document if anyone has used so far.reverse proxy.
    As basis person, we need to do all ( Apache installation, Apache configuration, Web dispatcher installation and configuration, integration with EP.)
    It will helpful to me if i can get Apache installation, Apache configuration part and integration with EP, or web dispatcher, configuration etc.
    Thanks,
    Deepak

    We used Netscaler for Reverse Proxy implementation and can assure you that network team performed most of the set ups. This was on EP 7.01.
    From BASIS stand point it would be primarily Web Dispatcher Configuration.
    Also refer the links I specified in another thread. There are several scenarios discussed there -
    Re: Post values for userid and passowrd fields in logon page
    http://wiki.sdn.sap.com/wiki/display/BSP/Using+Proxies
    ~ Dhanz

  • Getting String using ResourceBundle and XLIF resource bundle.

    Hello,
    I am using Jdev. 11.1.1.2.0. I am trying to use XLIFF resource bundle in the Model project and trying to get string from the bundle using following code. I am getting MissingResourceException. if I use Property Bundle, it works fine.
    public String getMessage(String code)
    return ResourceBundle.getBundle("model.ModelBundle").getString("MESSAGE1");
    Any help to make it work with XLIFF resource bundle will be appreciated.
    Thanks,
    Amit
    Edited by: Amit Patel on Apr 1, 2010 10:23 AM

    To get the values from the resource bundle, you use the <fmt:message> tag
    <fmt:message bundle="${appbundle}" key="lbl.accountnum"/>

  • Load Balance Reverse Poxy using ACE and HTTP Header Sticky

    Dear all,
    I have a reverse proxy that makes HTTP and HTTPS requests to an ACE.
    For implement persistence I want to configure HTTP HEADER Stickyness using the X-Forwarder-For information but I don't know:
    How to implement it ( I'l apreciate a little example about it).
    Which values I need for OFFSET and LENGHT fields.
    Can you help me please?
    Thanks a lot!!

    Hi Cesar.
    Thanks a lot for your answer but I think you misunderstand the question or I'm not explaninig very well
    I don't need to insert anything.
    The serverfarm X will be accesed by a reverse proxy. This reverse proxy already inserts the X-Forearder-From header, so the request from the reverse proxy comes with this header to the serverfarm X.
    The problem is that now, the serverfarm X sticky the client based on source IP. This is a wrong behavior becasue all the request comes form the same source (Reverse proxy) and all the load forwards to the same real IP address.
    This is because I want to change the sticky from source IP to HTTP header and looks for the X-Forwarder-For filed.
    Hop it will clarify the question!

  • How to split a string using IndexOf?

    How would you split a string using indexOf and not using the .split method?
    Any help is appreciated :D
    Message was edited by:
    billiejoe

    would it be better to use the first or the second?
    int      indexOf(int ch)
    Returns the index within this string of the first occurrence of the specified character.
    int      indexOf(int ch, int fromIndex)
    Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
    I think the second would be helpful. so how do i read it?

  • Setting current row using a string key in an iterator

    Hi ,
    I am using Studio Edition Version 11.1.1.6.0 and integrated wls.
    QUESTION:_
    As suggested by Sudipto i want to brief up my query.
    I have a master-detail relationship .Using that relation's Tree model i am displaying through an <af:iterator> . I want to set the current row in the iterator of the parent view object . Is there a way please help .
    Description:_
    I have 2 master-details tables . FormSections is the mater and SectionContents is the child.
    I have an use case and using the tree collection model in an iterator to display the nodes.The jsf page has the following markup
    <iterator id="i1" value="#{bindings.FormSectionsView1.collectionModel}"
    var="section">
    <decorativeBox id="db2">
    <facet name="top">
    <commandLink text="#{section.Sectionname}" id="cl1">
    <showPopupBehavior triggerType="action" popupId="p1"/>
    </commandLink>
    </facet>
    <facet name="center">
    <iterator id="i2" value="#{section.children}" var="field">
    <outputText value="#{field.Fieldlabel}" id="ot3"/>
    </iterator>
    </facet>
    </decorativeBox>
    </iterator>
    on the popup p1 i have #{DesignBean.createField} popupfetch listener.Now i want to insert a new row in the child when i click on the commandlink.
    I have tried the following
    1) Tried binding setCurrentRowWithKey and setCurrentRowWithKeyValue (namedvalue as #{section.Sectionid}) but there was no change i get the current row set to empty
    2) Tried using the following bean codes
    a) DCBindingContainer bindings =
    (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding sectionsIterator =
    (DCIteratorBinding)bindings.get("FormSectionsView1Iterator");
    System.out.println(sectionsIterator.getCurrentRow());
    String key_str="21";
    sectionsIterator.setCurrentRowWithKeyValue(key_str);
              executeOperationBindings("CreateInsert1");// child createinsert binding execution
         b)     DCBindingContainer bindings =
    (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding sectionsIterator =
    (DCIteratorBinding)bindings.get("FormSectionsView1Iterator");
    System.out.println(sectionsIterator.getCurrentRow());
    String key_str="21";
    Key key=sectionsIterator.createKey(key_str);
    if(key!=null)
    sectionsIterator.setCurrentRowWithKey(key.toStringFormat(true));
              executeOperationBindings("CreateInsert1");
              Now i have a problem of setting the parent to the current row on the iterator of the parent i am getting null pointer exception when tried to set the key.
    Thanks,
    Raj
    Edited by: RajaSekharReddy.M on Jan 30, 2013 6:11 AM
    Edited by: RajaSekharReddy.M on Jan 31, 2013 4:39 AM

    Rajasekhar ,
    What model layer do you use ? If ADF BC then shouldn't the parent child relationship already been defined as a View Link ?
    Also I'm a little confused as to why you are setting a hardcoded the key with a string , since you are clicking the command link from the row , you should be accessing it as
    #{section.sectionId}
    Also I didnot understand this line-
    Now i have a problem of setting the parent to the current row on the iterator of the parent i am getting null pointer exception when tried to set the key.A small tip is you can start giving briefly what you are trying to achieve and whats failing to get accurate replies . Please refer -
    https://forums.oracle.com/forums/ann.jspa?annID=56

  • Ipad2, I can not sign in to imessage after turning it off and doing a hard reboot. Upon entering my info it states no network connection, but I can use it o surf in Safari and iter websites. Any suggestions. Went on with Apple, they think its my network.

    Ipad2, I can not sign in to imessage after turning it off and doing a hard reboot. Upon entering my info it states no network connection, but I can use it o surf in Safari and iter websites. Any suggestions. Went on with Apple, they think its my network. All other wireless equipment can ign on without problems. This happened after I turned imessage off.

    Step by step, how did you arrive at seeing this agreement?

  • I use internode and imap. When the ipad deletes emails it also removes them from the mac. How can I reverse this so the mac is the master and the ipad is the slave?ipa

    I use internode and imap. When the ipad deletes emails it also removes them from the mac. How can I reverse this so the mac is the master and the ipad is the slave?

    Thanks for the info. - I now know that deletion works both ways!! - (unlike POP where emails deleted from the ipad also deleted them from the mac even before I could read them,  whereas emails deleted from the mac were not removed from the ipad!!! - ie. the ipad was the master over the mac - the slave).  Prior to changing to imap I used to transfer all nongarbage emails from inbox to mailboxes before my husband could ask if he could delete emails on his ipad. I have noticed however if you do this in imap, they are removed from the inbox on the ipad as well (this did not happen with POP). So we still have to check but the number is less so we like imap better than POP.
    Thank again

  • How do I use sqrt() and pow() math functions?

    I tried starting with import java.lang.Math.*; and using sqrt() and pow(), but I get an error response in compilation.
    //** 1/pi calculation program using Ramanujan's forumula **//
    //** by n=2 iteration, double precision value for 1/pi repeats **//
    import java.lang.Math.*;
    import java.io.*;
    public class CalcInversePiRamanujan {
      public static void main(String args[]) {
        double n=0, term, four_n_factorial=1, n_factorial=1, inverse_pi=0;
        inverse_pi = four_n_factorial * 1103 * 2 * sqrt(2) / 9801; //** initial value for n=0 **//
        System.out.println(inverse_pi);
        for (n=1, four_n_factorial=1, n_factorial=1; n<=3; n++) {
            four_n_factorial *= (4 * n);
            four_n_factorial *= (4*n-1);
            four_n_factorial *= (4*n-2);
            four_n_factorial *= (4*n-3);
            term = four_n_factorial;
            n_factorial *= n;
            term /= pow(n_factorial, 4);
            term *= 1103 + 26390 * n;
            term /= pow(396, 4 * n);
            term *= 2 * sqrt(2);
            term /= 9801;
            inverse_pi += term;
            System.out.println(n, term, inverse_pi);
        System.exit(0);
    }

    all methods in math class are static so you have to call them as
    Math.pow() and Math.sqrt() you dont have to import any additional packages as Math is a class available in java.lang package
    you have to change your
    System.out.println(n, term, inverse_pi); to
    System.out.println(n+ term+ inverse_pi);
    math class also provides the value of Pi you can access it using Math.PI

  • Command link / button action is not taking place if i use it in iterator.

    Hi,
    I am new to ADF, i am facing 1 issue while implementing ADF mobile browser application.
    Issue: command link / button action is not taking place if i use it in iterator. its just refreshing the page it self and displaying as no records.
    Scenario is i am populating the search results in results page from search page using iterator, i want to get the complete details in different page (results page -> details page) .
    I have tried in different ways.like
    case1:
    <tr:panelGroupLayout id="pgl2" layout="vertical" styleClass="af_m_panelBase">
    <tr:panelHeader text="#{classviewBundle.SEARCH_RESULTS}" id="ph1"/>
    <tr:iterator id="i1" value="#{bindings.SubjectVO1.collectionModel}" var="subject"
    varStatus="subIndx" rows="100">
    <tr:panelBox text="#{subject.Subject} #{subject.CatalogNbr} - #{subject.CourseTitleLong}"
    styleClass="af_m_listingPrimaryDetails" id="pb1">
    <f:facet name="toolbar"/>
    <tr:table var="ssrClass" rowBandingInterval="1" id="t1" value="#{subject.children}"
    varStatus="clsIndx" rowSelection="none"
    binding="#{SessionBean.subjectTable}" verticalGridVisible="true"
    emptyText="No Records" width="100%">
    <tr:column id="c9" sortable="false" styleClass="width:100%">
    <*tr:commandLink text="Section: #{ssrClass.ClassSection}-#{ssrClass.SsrComponentLovDescr} (#{ssrClass.ClassNbr})"*
    id="commandLink2" styleClass="af_m_listingLink"
    *action="#{pageFlowScope.BackingBean.searchaction}"></tr:commandLink>*
    //remaining code
    in this case commandlink action is not able to invoke serachaction() method
    case 2:
    <tr:commandLink text="Section: #{ssrClass.ClassSection}-#{ssrClass.SsrComponentLovDescr} (#{ssrClass.ClassNbr})"
    id="commandLink2" styleClass="af_m_listingLink"
    action="classdetails}"></tr:commandLink>
    in this case its not able to navigate to classdetails page.
    I gave correct navigation cases and rules in taskflow,but its working fine when the command link is out of iterator only.
    i tried with actionlistener too.. but no use.. please help me out of this problem .
    *Update to issue:*
    The actual issue is when i use command link/button in an table/iterator whose parent tag is another iterator then the action is not taking place.
    the structer of my code is
    < iterator1>
    #command link action1
    < iterator2>
    #command link action2
    </ iterator2>
    < /iterator1>
    #command link action1 is working but "#command link action2" is not...
    Thanks
    Shyam
    Edited by: shyam on Dec 26, 2011 5:40 PM

    Hi,
    To solve my problem I used a af:foreach instead.
    <af:forEach items="#{viewScope.DataBySubjectServiceBean.toArray}" var="text">
    <af:commandLink text="#{text.IndTextEn}" action="indicator-selected" id="cl1">
    <af:setActionListener from="#{text.IndCode}" to="#{pageFlowScope.IndicatorCodeParam}" />
    </af:commandLink>
    </af:forEach>
    By the way you need to convert the iterator to an Array using a ManagedBean.
    public Object[] toArray() {
    CollectionModel cm = (CollectionModel) getEL("#{bindings.TView1.collectionModel}");
    indicators = new Object[cm.getRowCount()];
    for(int i=0;i<cm.getRowCount();i++){
    indicators[i] = cm.getRowData(i);
    return indicators;
    public static Object getEL(String expr) {
    FacesContext fc = FacesContext.getCurrentInstance();
    return fc.getApplication().evaluateExpressionGet(fc,expr,Object.class);
    Hope that helps-
    Edited by: JuJuZ on Jan 3, 2012 12:23 AM
    Add getEL Method

  • CC Compiler barfs when replacing string using istreambuf_iterator.

    Hi All,
    I am a noobie to Solaris.
    The following piece of code when compiled with g++ works fine.
    But Solaris CC compiler barfs.
    #include <iostream>
    #include <fstream>
    #include <iterator>
    #include <string>
    using namespace std;
    std::string stlString("test for string.assign() method");
    int main () {
      filebuf fb;
      fb.open ("test.txt",ios::in);
      istream is(&fb);
      istreambuf_iterator<char> itr(is);
      istreambuf_iterator<char> end;
      std::cout << "before : " << stlString << std::endl;
      stlString.assign(itr, end);
      //while ((itr != end) && (*itr != '\n')) stlString+=*itr++;
      std::cout << "after : " << stlString << std::endl;
      fb.close();
      return 0;
    $ cat test.txt
    this is a sample file
    $ g++ -m32 -Wall -g istreambuf.cc
    $ ./a.out
    before : test for string.assign() method
    after : this is a sample file
    $
    ==========================
    $ CC -m32 -g istreambuf.cc -library=iostream
    "istreambuf.cc", line 20: Error: Could not find a match for std::string::assign(std::istreambuf_iterator<char, std::char_traits<char>>, std::istreambuf_iterator<char, std::char_traits<char>>) needed in main().
    1 Error(s) detected.Any help is appreciated.
    I need the code to be compiled on both (CC and g++).
    Any help is appreciated.
    Thanks in advance,
    Sreekar

    The default standard library (Cstd) doesn't have any member templates. For a more standard behavior, you want -library=stlport4 (or possibly stdcxx on solaris 11).

  • Not able to create More than 1 Partition in USB Drive using kernel32 and DeviceIoControl

    I have successfully created 2 or more partitions in USB drive using DeviceIoControl in C++. Now I am trying to convert this code into C# using kernel32 and DeviceIoControl. But I am not getting more than 1 partition. Can anybody tell me what is wrong
    with this code?
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    namespace PartitionWrapper
    public class IOWrapper
    public static bool CreatePartitions(string selectedDrive)
    bool RetCode = false;
    try
    bool bSuccess = false;
    uint dwBytesReturned = 0;
    IntPtr hDisk = OpenVolume(selectedDrive);
    if (hDisk == null || hDisk == FSConstants.INVALID_HANDLE_VALUE)
    RetCode = false;
    goto FINAL;
    bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_DELETE_DRIVE_LAYOUT, IntPtr.Zero, 0, default(IntPtr), default(uint), ref dwBytesReturned);
    // Get the partition information
    uint PartitionInfomations = (uint)(Marshal.SizeOf(typeof(FSStructures.DRIVE_LAYOUT_INFORMATION_EX)) + 3 * Marshal.SizeOf(typeof(FSStructures.PARTITION_INFORMATION_EX)));
    byte[] DBuffer = new byte[PartitionInfomations];
    GCHandle handle = GCHandle.Alloc(DBuffer, GCHandleType.Pinned);
    FSStructures.DRIVE_LAYOUT_INFORMATION_EX pDriveLayout = (FSStructures.DRIVE_LAYOUT_INFORMATION_EX)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FSStructures.DRIVE_LAYOUT_INFORMATION_EX));
    IntPtr pDriveLayoutPtr = Marshal.AllocHGlobal(Marshal.SizeOf(pDriveLayout));
    Marshal.StructureToPtr(pDriveLayout, pDriveLayoutPtr, false);
    // bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, default(IntPtr), default(uint), pDriveLayoutPtr, PartitionInfomations, ref dwBytesReturned);
    pDriveLayout = (FSStructures.DRIVE_LAYOUT_INFORMATION_EX)Marshal.PtrToStructure(pDriveLayoutPtr, typeof(FSStructures.DRIVE_LAYOUT_INFORMATION_EX));
    if (bSuccess || dwBytesReturned != PartitionInfomations)
    RetCode = true;
    else { RetCode = false; goto FINAL; }
    pDriveLayout.PartitionEntry = new FSStructures.PARTITION_INFORMATION_EX[0x16];
    pDriveLayout.PartitionStyle = FSStructures.PARTITION_STYLE.MasterBootRecord;
    pDriveLayout.PartitionCount = 4;
    pDriveLayout.DriveLayoutInformatiton.Mbr.Signature = 0xA4B57300;
    pDriveLayout.PartitionEntry[0] = new FSStructures.PARTITION_INFORMATION_EX();
    pDriveLayout.PartitionEntry[0].PartitionStyle = FSStructures.PARTITION_STYLE.MasterBootRecord;
    pDriveLayout.PartitionEntry[0].Mbr.BootIndicator = true;
    pDriveLayout.PartitionEntry[0].Mbr.RecognizedPartition = true;
    pDriveLayout.PartitionEntry[0].Mbr.PartitionType = 0x0B;
    pDriveLayout.PartitionEntry[0].PartitionNumber = 1;
    pDriveLayout.PartitionEntry[0].StartingOffset = 32256;
    pDriveLayout.PartitionEntry[0].PartitionLength = 3221225472;
    pDriveLayout.PartitionEntry[0].RewritePartition = true;
    pDriveLayout.PartitionEntry[0].Mbr.HiddenSectors = 32256 / 512;
    pDriveLayout.PartitionEntry[1] = new FSStructures.PARTITION_INFORMATION_EX();
    pDriveLayout.PartitionEntry[1].PartitionStyle = FSStructures.PARTITION_STYLE.MasterBootRecord;
    pDriveLayout.PartitionEntry[1].Mbr.BootIndicator = false;
    pDriveLayout.PartitionEntry[1].Mbr.RecognizedPartition = true;
    pDriveLayout.PartitionEntry[1].Mbr.PartitionType = 0x0B;
    pDriveLayout.PartitionEntry[1].PartitionNumber = 2;
    pDriveLayout.PartitionEntry[1].StartingOffset = 32256 + 3221225472;
    pDriveLayout.PartitionEntry[1].PartitionLength = 2147483648; //2147483648;//3221225472;
    pDriveLayout.PartitionEntry[1].RewritePartition = true;
    pDriveLayout.PartitionEntry[1].Mbr.HiddenSectors = 32256 / 512;
    for (int i = 0; i < pDriveLayout.PartitionEntry.Length; i++)
    pDriveLayout.PartitionEntry[i].RewritePartition = true;
    try
    bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_SET_DRIVE_LAYOUT_EX, ref pDriveLayout, PartitionInfomations, default(IntPtr), default(uint), ref dwBytesReturned);
    catch (Exception ex)
    if (bSuccess)
    RetCode = true;
    else { RetCode = false; }
    bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_UPDATE_PROPERTIES, IntPtr.Zero, 0, default(IntPtr), default(uint), ref dwBytesReturned);
    if (bSuccess)
    RetCode = true;
    else { RetCode = false; }
    FINAL:
    // Close the disk handle.
    if (hDisk != null && hDisk != FSConstants.INVALID_HANDLE_VALUE)
    FSStructures.CloseHandle(hDisk);
    catch { return false; }
    return RetCode;
    private static IntPtr OpenVolume(string DeviceName)
    try
    IntPtr hDevice;
    hDevice = FSStructures.CreateFile(
    @"\\.\" + DeviceName,
    FSConstants.GENERIC_EXECUTE | FSConstants.GENERIC_READ | FSConstants.GENERIC_WRITE | FSConstants.FILE_SHARE_READ | FSConstants.FILE_SHARE_WRITE,
    FSConstants.FILE_SHARE_WRITE,
    IntPtr.Zero,
    FSConstants.OPEN_EXISTING,
    0,
    IntPtr.Zero);
    if ((int)hDevice == -1)
    throw new Exception(Marshal.GetLastWin32Error().ToString());
    return hDevice;
    catch { return FSConstants.INVALID_HANDLE_VALUE; }
    internal static class FSConstants
    public const uint FILE_SHARE_READ = 0x00000001;
    public const uint FILE_SHARE_WRITE = 0x00000002;
    public const uint OPEN_EXISTING = 3;
    public const int GENERIC_EXECUTE = 0x10000000;
    public const uint GENERIC_READ = (0x80000000);
    public const uint GENERIC_WRITE = (0x40000000);
    public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
    public const uint IOCTL_DISK_GET_DRIVE_LAYOUT_EX = 0x00070050;
    public const uint IOCTL_DISK_SET_DRIVE_LAYOUT_EX = 0x7C054;
    public const int IOCTL_DISK_UPDATE_PROPERTIES = 0x70140;
    public const int IOCTL_DISK_DELETE_DRIVE_LAYOUT = 0x0007c010;
    public const int IOCTL_DISK_CREATE_DISK = 0x7C058;
    internal static class FSStructures
    [DllImport("kernel32.dll", EntryPoint = "CreateFile", SetLastError = true)]
    public static extern IntPtr CreateFile(
    string lpFileName,
    uint dwDesiredAccess,
    uint dwShareMode,
    IntPtr lpSecurityAttributes,
    uint dwCreationDisposition,
    uint dwFlagsAndAttributes,
    IntPtr hTemplateFile);
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern int CloseHandle(IntPtr hObject);
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool DeviceIoControl(
    IntPtr hDevice,
    uint dwIoControlCode,
    [Optional]ref DRIVE_LAYOUT_INFORMATION_EX lpInBuffer,
    uint nInBufferSize,
    [Optional] [Out] IntPtr lpOutBuffer,
    uint nOutBufferSize,
    [Optional] ref uint lpBytesReturned,
    [Optional] IntPtr lpOverlapped);
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool DeviceIoControl(
    IntPtr hDevice,
    uint dwIoControlCode,
    IntPtr lpInBuffer,
    uint nInBufferSize,
    [Optional] [Out] IntPtr lpOutBuffer,
    uint nOutBufferSize,
    [Optional] ref uint lpBytesReturned,
    [Optional] IntPtr lpOverlapped);
    [StructLayout(LayoutKind.Sequential)]
    public struct DRIVE_LAYOUT_INFORMATION_EX
    public PARTITION_STYLE PartitionStyle;
    public int PartitionCount;
    public DRIVE_LAYOUT_INFORMATION_UNION DriveLayoutInformatiton;
    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 0x16)]
    public PARTITION_INFORMATION_EX[] PartitionEntry;
    [StructLayout(LayoutKind.Sequential)]
    public struct PARTITION_INFORMATION_EX
    [MarshalAs(UnmanagedType.U4)]
    public PARTITION_STYLE PartitionStyle;
    public long StartingOffset;
    public long PartitionLength;
    public int PartitionNumber;
    public bool RewritePartition;
    public PARTITION_INFORMATION_MBR Mbr;
    public PARTITION_INFORMATION_GPT Gpt;
    [StructLayout(LayoutKind.Sequential)]
    public struct PARTITION_INFORMATION_MBR
    public byte PartitionType;
    [MarshalAs(UnmanagedType.U1)]
    public bool BootIndicator;
    [MarshalAs(UnmanagedType.U1)]
    public bool RecognizedPartition;
    public uint HiddenSectors;
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct PARTITION_INFORMATION_GPT
    public Guid PartitionType;
    public Guid PartitionId;
    [MarshalAs(UnmanagedType.U8)]
    public EFIPartitionAttributes Attributes;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)]
    public string Name;
    [Flags]
    public enum EFIPartitionAttributes : ulong
    GPT_ATTRIBUTE_PLATFORM_REQUIRED = 0x0000000000000001,
    LegacyBIOSBootable = 0x0000000000000004,
    GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = 0x8000000000000000,
    GPT_BASIC_DATA_ATTRIBUTE_HIDDEN = 0x4000000000000000,
    GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY = 0x2000000000000000,
    GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY = 0x1000000000000000
    [StructLayout(LayoutKind.Explicit)]
    public struct DRIVE_LAYOUT_INFORMATION_UNION
    [FieldOffset(0)]
    public DRIVE_LAYOUT_INFORMATION_MBR Mbr;
    [FieldOffset(0)]
    public DRIVE_LAYOUT_INFORMATION_GPT Gpt;
    [StructLayout(LayoutKind.Sequential)]
    public struct DRIVE_LAYOUT_INFORMATION_GPT
    public Guid DiskId;
    public long StartingUsableOffset;
    public long UsableLength;
    public int MaxPartitionCount;
    [StructLayout(LayoutKind.Sequential)]
    public struct DRIVE_LAYOUT_INFORMATION_MBR
    public uint Signature;
    public enum PARTITION_STYLE : int
    MasterBootRecord = 0,
    GuidPartitionTable = 1,
    Raw = 2

    Hello,
    in the links below you can found many informations to help you:
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa365730(v=vs.85).aspx
    http://www.codeproject.com/Articles/696388/Recover-Data-From-Corrupted-Drives-File-Systems-FA
    http://www.functionx.com/vcsharp/fileprocessing/drives.htm
    http://forums.codeguru.com/showthread.php?548305-partitioning-USB-Falsh-drive
    http://forums.codeguru.com/showthread.php?548169-USB-Flash-drive-Partitioning

  • XML - 0112 Error on parsing using SAX and xml file in InputSource object.

    I need to parse a XML string and extract some information. I have to use SAX parser. I'm converting hte string to InputSource and then trying to parese.
    i'm getting XML-0112 error, my guess is that it is not able to locate DTD file but i tried hardcoding the whole path in DOCTYPE tag.
    i tried doing setSystemId also but no luck.
    null

    Can you post a simple test case to look at?

Maybe you are looking for

  • Flash Player crashes when accessing my webcam

    Hello, I am using about 20 different HP Elitepad 900 G1 tablets (all 32 bit OSes). On each one, when signing into MegaMeeting and being prompted to access the webcam, IE stops responding. When I try the same thing in Firefox, it states that Flash Pla

  • Unusual Bug when creating pdf from image files

    Hi I have a very mindboggling problem which I cant seem to get my head around. basically I am trying to create a pdf using a large amount of image files, these images are scans of pages of a book. so I have been trying to create a pdf file from these

  • Extract highlighted text in PDF

    Hi,   I want to write a tool which can extract highlighted text from the pdf and export the text into another pdf file. Can somebody give me directions how to do that. if you think some tool already has that capacity, please let me know. Most of the

  • Deleted com.apple.windowserver.plist

    Hi everyone. I deleted the com.apple.windowserver.plist, under preferences and the longer version under my user profile. Supposidly,the system would recreate these files on restart.  It has not and the files are gone. Now I can't enable quartz extrem

  • Check CRM Error Flag of Workflow Condition in own Code Condition

    Hi everybody, I am creating an own condition with the help of a badi. Can any body tell me how to check if a ticket has an error message like the CRM Error Flag in the Work Flow Condition`? Regards Ali