Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

String manipulation

  • 24-10-2006 4:32pm
    #1
    Registered Users, Registered Users 2 Posts: 618 ✭✭✭


    hi guys,

    I am wondernig can anybody help me, I have an input (String) for example "1122334455FF" and what I am looking to do is to break down down
    like:
    "11 22 33 44 55 FF", so a space is inserted after every second value.

    any help would be great.

    thanks.....


Comments

  • Registered Users, Registered Users 2 Posts: 205 ✭✭Stugots


    The resulting string is going to be larger than the first string, so you need to figure out the size of the resulting string and allocate enough memory for that. Then its just a simple loop copying the data from the first string to the allocated buffer and inserting a space after every two characters.


  • Registered Users, Registered Users 2 Posts: 68,317 ✭✭✭✭seamus


    Is this an assignment? What language are you using?

    Post up some code, or even your own ideas that you've done already. This is a simple problem, so it seems like a college/homework assignment, so you'll need to show that you've done some work on this first.


  • Registered Users, Registered Users 2 Posts: 618 ✭✭✭smithslist


    sorry guys i forgot to mention it, it is in java and it is something somebody in work asked me and i was confused how to do it.

    but got it working....here is the code that after every two single char a space is placed, thus "112233445566" becomes "11 22 33 44 55 66"

    String string = "112233445566";
    if (string.length() < 3)
    {
    }
    else {
    String firstTok = string.substring(0,2);
    String leftover = string.substring(2,string.length());
    string = firstTok+" "+recursive_thing(leftover);
    string = firstTok+" "+recursive_thing(leftover);
    }
    System.out.println("string "+string);

    hope it helps none who needs it

    thanks...........


  • Registered Users, Registered Users 2 Posts: 618 ✭✭✭smithslist


    was told there is a simplier way of doing it, simplier meaning for beginners (in programming) to understand better.......nbody knows a way wuld b good

    quite amazed how a simple task wreck my head for so long......


  • Registered Users, Registered Users 2 Posts: 7,468 ✭✭✭Evil Phil


    Is the string always going to be of a fixed length? You should try looping through the string if not.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 618 ✭✭✭smithslist


    no its aint a fix string, but I stated to do something like this, the string would have to b even.....so I told her to introduce a try catch exception to check on input if the length is a even length or not.

    try
    {
    string = string.trim();
    if (string.length() % 2 != 0)
    {
    throw new Exception();
    }

    }
    catch (Exception e)
    {
    MainClass.displayErrorMessage("blah blah " + string);
    return;
    }


  • Registered Users, Registered Users 2 Posts: 590 ✭✭✭dal


    public static String insertSpaces (String input)
    {
    	StringBuffer stringbuffer = new StringBuffer();
    	
    	int insertSpaceIndex = 2;
    	int inputStringLength = input.length();
    	
    	int i = 0;
    	while (i + insertSpaceIndex <= inputStringLength)
    	{
    		stringbuffer.append(input.substring(i, i + insertSpaceIndex) + " ");
    		i = i + insertSpaceIndex;
    	}
    	
    	return stringbuffer.toString();
    }
    

    You could use that, though it will append a space on the very last iteration as well, though this is easily avoided.


  • Registered Users, Registered Users 2 Posts: 5,618 ✭✭✭Civilian_Target


    How about:
    public String addSpaces(String noSpaces)
    {
        if(noSpaces.length() > 2)
            return noSpaces.substring(0,2) +" " +addSpaces(noSpaces.substring(2,noSpaces.length()));  
        return noSpaces;
    }
    

    Goddamn typo


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    in java can you not threat a string as a charactor array? well deep down this is what it really is but i never worked with java so don't know.

    What i would do this and detect if it is an even number and place a space in if it was. For example in c++
    string mystring = "1122334455FF";
    int numofextraspaces = mystring.size()/3;
    
    char outputstring[15] = "";
    int lastpos;
    bool changed =false;
    
    	for (int k = 1; k < mystring.size()+numofextraspaces; k++)
    	{
    	    
    	    if (!changed)
    	    	lastpos = k-1;
    
    	    
    	     if (k%3==0)
    	       {
    	       		outputstring[k-1]= '  ';
    	       		lastpos = k-1;
    	       		changed = true;
    	        }
    	        
    	     else
    	        {
    	        	outputstring[k-1] = mystring[lastpos];
    
    	        }
    
    	}
    

    Very simple, hope that would work though.


  • Registered Users, Registered Users 2 Posts: 5,618 ✭✭✭Civilian_Target


    Surely that's just going to overwrite every evenly numbered character with a space?


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    well its k, it doing the calculatino on, not the charactor. So its positions its dealing with, not values. But i just noticed that that will do a space at start and every second one after that.

    edit: fixed


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    Nice idea, but what that code does is replace (oerwrite) every third character with a ' '. Not quite what is wanted :P

    EDIT: smithslist, it's perfectly ok to ask questions about homework here so long as you show that you've done some work at the problem and can explain what your code *isn't* doing right. But tbh i really doubt the "someone asked me in work" story, unless of course work is teaching you and your friend to learn very basic coding skills using java...


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    it overwrites it with a space as far as i can see :), but if that causes difficulty i suppose you could cast the ASCII code.

    Edit: Ok i see the problem, my mistake :) - once again!
    You could use a ready made functino or a custom made one to shift all elements right to create holes to insert the spaces i suppose

    Right i don't want to even explain this:
    string mystring = "1122334455FF";
    int numofextraspaces = mystring.size()/3;
    
    char outputstring[15] = "";
    int lastpos;
    bool changed =false;
    
    	for (int k = 1; k < mystring.size()+numofextraspaces; k++)
    	{
    	    
    	    if (!changed)
    	    	lastpos = k-1;
    
    	    
    	     if (k%3==0)
    	       {
    	       		outputstring[k-1]= '  ';
    	       		lastpos = k-1;
    	       		changed = true;
    	        }
    	        
    	     else
    	        {
    	        	outputstring[k-1] = mystring[lastpos];
    
    	        }
    
    	}
    

    but it doesn't work properly. See you need a constant to create the charactor array, and unfort you don't know the size of the string until you enter the program. I'm sure there is some smart way of allocating memory dynamically?

    I'm giving up, its doesn't include the 44 in the new string. Got assignments to do myself but id spend more time if i could. Might give some ideas


  • Registered Users, Registered Users 2 Posts: 618 ✭✭✭smithslist


    Mutant_Fruit i dont wanna get into form wars or nthing, but i did programming years ago in coll, even thou it wasnt much but it was basic, and thats why here i post this query and others b4 this to help me (and work pals) out wit queries lik the one above.....

    i am learnin to program again in my company, and one of my work pals (only recently joined) hence "someone asked me in work", asked me the q bout it, and i wanted to help her out.......so dat is why

    once again, thanks to all who helped me out, much appreciated....thanks


  • Closed Accounts Posts: 286 ✭✭Kev


    Theres hundreds of ways of doing it, heres one in one line of code

    string = string.replaceAll( "(..)", "$1 " );

    note: won't work on ancient jdk's


  • Closed Accounts Posts: 286 ✭✭Kev


    Modification to ensure it doesn't add a space at the end

    string = string.replaceAll( "(..)(?!$)", "$1 " );


  • Registered Users, Registered Users 2 Posts: 5,112 ✭✭✭Blowfish


    Kev wrote:
    string = string.replaceAll( "(..)(?!$)", "$1 " );
    ^ i'd definitely agree with this one, it's too the point, and the most efficient.


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    :) A hell lot easier and quicker than my approach


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    string start = "aabbccddeeff";
    string result = null;
    for(int i = 0; i < start.Length; i++)
    {
        // If we're not at the start AND we're not at the very end
        // AND we've copied 2 characters since our last space was entered
        if((i != 0) && (i % 2 == 0) && (i != start.length-1))
            result += " ";
    
        result += start[i];
    }
    
    // result should now equal: "aa bb cc dd ee ff"
    

    There are nicer ways of doing it with regex, but that's a simple way of doing it, assuming your chosen language allows string concateration. I'm too lazy to write a C version which does the same thing ;) Also, i didn't compile or test this, but i assume it works. 10 bonus points if i made a mistake :p


  • Registered Users, Registered Users 2 Posts: 590 ✭✭✭dal


    string start = "aabbccddeeff";
    string result = null;
    for(int i = 0; i < start.Length; i++)
    {
        // If we're not at the start AND we're not at the very end
        // AND we've copied 2 characters since our last space was entered
        if((i != 0) && (i % 2 == 0) && (i != start.length-1))
            result += " ";
    
        result += start[i];
    }
    
    // result should now equal: "aa bb cc dd ee ff"
    

    There are nicer ways of doing it with regex, but that's a simple way of doing it, assuming your chosen language allows string concateration. I'm too lazy to write a C version which does the same thing ;) Also, i didn't compile or test this, but i assume it works. 10 bonus points if i made a mistake :p
    Being extra pedantic here, but in java its generally bad practice to concatenate in this way as it actually creates a brand new String object every single time (Strings are immutable). Its better to use a Stringbuffer and to append.


  • Advertisement
  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    I agree 100% :p A far better solution would be a StringBuilder, but i wasn't going to complicate the issue ;)

    String arithmetic in languages with immutable strings is a bad idea. Then again, if you're only doing 2-4 string "additions" then you're sometimes best not using a StringBuilder. It all depends.


Advertisement