Java add spaces to string

By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I just want to add a space between each character of a string. Can anyone help me figuring out how to do this? Basically it says "Replace all characters except the last one with with the character itself followed by a space".

Blow up your String into array of chars, loop over the char array and create a new string by succeeding a char by a space. This is the same problem as joining together an array with commas. This version correctly produces spaces only between characters, and avoids an unnecessary branch within the loop:.

If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete. Learn more. Add spaces between the characters of a string in Java?

Ask Question. Asked 8 years, 7 months ago. Active 1 year, 2 months ago.

java add spaces to string

Viewed k times. Jey Jey 2 2 gold badges 4 4 silver badges 6 6 bronze badges. This is homework, right? If so, then tag it with the homework tag. What have you tried.

Have you read the String javadoc? Active Oldest Votes. Unless you want to loop through the string and do it "manually" you could solve it like this: yourString. At last Bohemian - It may be a one-liner, but not everyone will understand it. I mean simply asking how did you form the ". It ll be a great help. This answer whilst its the best of the lot here, does not consider the level of understanding of the OP.

Petar Minchev Petar Minchev Swagatika Swagatika 3, 5 5 gold badges 26 26 silver badges 38 38 bronze badges. Bohemian : I already read and also voted up.

I am new to regex, so dint quite understand. Swagatika: Don't blindly follow his advice. Regexes are an interesting tool, but involve a performance hit and of course are harder to read to many programmers.

java add spaces to string

Use what is most appropriate. Also: You may not have recognized, but there's a high dose of arrogance in Bohemians post, and arrogance should always make you skeptical.Campbell Ritchie wrote: You can try all sorts of things with a String builder. You can replace a stretch of text, or delete and insert. You can get index of "items" and insert just before that. There is even a section in the Java Tutorials about it. Try it; it is quite easy. Forum: Java in General.

Sudhir Srinivasan. I'm using the same in my program to right justify numbers. Numbers start with 2 single-digit and increase in multiples of 2 containing n no. I would like to replace String. Rest of the program code not posted for brevity and also my concern is with the padAgain String, int method shown.

If required, will post the entire code for reasons of clarity. Thanks, Sudhir. Campbell Ritchie. You can try all sorts of things with a String builder. Thank you for your suggestions and the sample code. Will certainly read up on Java Tutorialsimplement the same in my program and revert for further clarifications, if any.

How To Add Space in string

Regards, Sudhir. Would therefore appreciate your help again. Within this, invoke the indexOf String by passing 'result' as a substring of itself and insert blank space at position 0 upto max.

Got it! From the looks of it, I've unnecessarily complicated with multiple insert calls et al. The spaces can be replaced with special characters by using the appropriate StringBuilder method within the loop construct. This guy is skipping without a rope. At least, that's what this tiny ad said:. Boost this thread! Convert decimal value to binary. Binary to Decimal conversion.Pad to the left and to the right with string. Format codes. Padding strings.

A padded string has leading or trailing spaces up to a certain number of characters. But no built-in "padding" method is available on the String class. Instead, we implement padding with format strings and the String.

We can specify left and right padding. We can pad strings and numbers. First example. This program left-justifies color names and right-justifies a parallel array of ints. We do this with just one format string. Pad, right: The code s adds right-padding to a string. We must specify the minus sign here. Pad, left: The code 10d adds left padding to an integer "s" would handle a string. Result: The format string applies padding to two values at once.

This is efficient and correct. Java program that uses padding, String. Right-justify the number. This program shows how the String.

It uses a total width of 10 chars. Result: The string "Ulysses" is 7 chars, so 3 space chars are added to the start to get to 10 chars. Here we left-justify a string.

Trim (Remove leading and trailing spaces) a string in Java

We expand the string to 20 chars, adding spaces on the right as needed. We must specify the minus sign.Mar 16, Core JavaExamplesString comments. Noticed that we incorporated a counter in the logic so that it is clear how many tokens were found. The output is shown below. Apple 2. Banana 3.

Here is the sample output. Notice that the four items were correctly identified. Cat 2. Dog 3. Elephant 4. And the output is still as expected. Fox 5. Here is a sample output. Notice that each consecutive whitespace will result to an empty String item in the resulting array. Dog 4. Elephant 8. Home Learn Java Programming. Recent Posts. This is useful, for example, when we want to retrieve all the words in a text document.

The whitespaces are the markers that separates each word.

java add spaces to string

Split is very powerful because you can specify the delimiter via regular expression. It can save a lot of time because of the power of regex. Split by single space If we have the String "Apple Banana Carrot"we can see that there are 3 words separated by single spaces. Carrot The animal array contains three items in this case. Here is an example code that parses a String separated by multiple spaces. Goat The animal array contains five items in this case.

Fox The animal array contains twelve items in this case, where eigth are empty Strings.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the true length of the string.

USE character array to perform this operation in place. The basic algorithm is probably as good as it gets as a character array system. Your code, given the input conversion "abc ", 3 you would output "abc" but you should not remove any "extra" padding in the string, you should return "abc ". In fact, you should only really have the one char[] array. The second one is making you do bad things. Comment unusual loops - your second for-loop is an odd one, and it often helps the reader if you comment why a loop is non-sequential or even if you just make sure they are aware of it.

Have you considered having a separate index for each position in the array - the position of the source character, and the position of where to insert it?

The benefit of two indexes is that you can keep the logic more readable You have re-invented the wheel which makes for a rather poor answer to an interview question Academic context would be different. A good interview answer emphasises knowledge of the inbuilt capabilities balanced with an appreciation of development priorities.

Simple code that uses inbuilt libraries is quick to code, robust, widely understandable and maintainable. I would expect to see something like:. Expanding on Interview aspect The ability to stick closely to the requirements is an important skill in a developer but should not mean blindly following them.

The specification is a reflection of requirements. Requirements shouldn't specify implementation details and may be in error.

Subscribe to RSS

Spotting bogus things and having the strength of character to call them out in a constructive manner are important skills in a developer. As an interviewer I will often ask the impossible or unreasonable question. It is not there to trick you or catch you out, it is to test how you will react to something you will encounter in reality.

How come nobody notices the name of the method conversion? Shouldn't your method names be verbs? According to the problem statement, the String passed in has enough room to hold all the expanded characters, and you are supposed to do the expansion in-place. You went ahead and allocated a second character array and copied the characters from one array to another.

The whole backwards loop you used only makes sense if you are expanding in-place in the same array. If you allocate a new array, you might as well write the loop in the forwards direction since it doesn't make any difference.

Here is how I would have modified your function. It looks a lot like rolfl's version actually :. How to split a string in Java. A tad bit on the concerned side here as I am not sure if your goal is a brute force coding requirement or not but the above link shows how to use the string split function an example is.

Sign up to join this community. The best answers are voted up and rise to the top. Home Questions Tags Users Unanswered. Asked 3 years, 1 month ago. Active 1 year, 4 months ago.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service.

The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Every string should take 30 characters and after I check its length I want to add whitespaces to the end of the string. You can use String.

PadRight for this. Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length. PadRight method for this. Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.

PadRight adds spaces to the right of strings. It makes text easier to read or store in databases. Padding a string adds whitespace or other characters to the beginning or end. PadRight supports any character for padding, not just a space.

java add spaces to string

Use String. PadRight which will space out a string so it is as long as the int provided. Learn more. Adding whitespaces to a string in C Ask Question. Asked 7 years ago. Active 1 month ago. Viewed 73k times.

I'm getting a string as a parameter. The question is, how do I add whitespaces to a string? Shekhar 2, 2 2 gold badges 35 35 silver badges 45 45 bronze badges. I think this question relates to the following post: stackoverflow. Active Oldest Votes. PadRight 30. RedFilter RedFilter k 32 32 gold badges silver badges bronze badges. PadRight method for this; Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.

PadRight 10 ; Console. Write s ; Console. WriteLine "feline" ; Console.Campbell Ritchie wrote: You can try all sorts of things with a String builder. You can replace a stretch of text, or delete and insert. You can get index of "items" and insert just before that. There is even a section in the Java Tutorials about it.

Try it; it is quite easy. Forum: Java in General. Sudhir Srinivasan. I'm using the same in my program to right justify numbers. Numbers start with 2 single-digit and increase in multiples of 2 containing n no.

I would like to replace String. Rest of the program code not posted for brevity and also my concern is with the padAgain String, int method shown. If required, will post the entire code for reasons of clarity. Thanks, Sudhir. Campbell Ritchie. You can try all sorts of things with a String builder. Thank you for your suggestions and the sample code. Will certainly read up on Java Tutorialsimplement the same in my program and revert for further clarifications, if any.

Regards, Sudhir. Would therefore appreciate your help again. Within this, invoke the indexOf String by passing 'result' as a substring of itself and insert blank space at position 0 upto max.

Got it! From the looks of it, I've unnecessarily complicated with multiple insert calls et al. The spaces can be replaced with special characters by using the appropriate StringBuilder method within the loop construct. There's a way to do it better - find it. A better tiny ad:.

Java – Right pad a string with spaces or zeros

Boost this thread! Convert decimal value to binary. Binary to Decimal conversion.


thoughts on “Java add spaces to string

Leave a Reply

Your email address will not be published. Required fields are marked *