Reputation: 17
I'm trying to create a method where the currentString is returned with underscores in the middle of each character. For example, if the current string is: "hi there" the output string would be h_i__t_h_e_r_e
with no underscore at the beginning or end. I'm aware this can be done with regex and replaceAll, but I'm trying to accomplish this with a for loop instead
My current code looks like this:
public String spacedWord()
{
String spacedString = "";
for (int i = 0; i<currentString.length(); i++)
{
spacedString = spacedString+currentString.charAt(i)+"_";
}
return spacedString;
}
If the current string is "hey there" my code returns h_e_y_ _t_h_e_r_e_
with an underscore at the end.
The code returns properly with underscores in between each character, but I'm not sure how make sure an underscore doesn't appear at the end of the string.
Any help is appreciated!
Upvotes: 0
Views: 155
Reputation: 2427
I think you can try with this code piece as well. The concept here is to delay the appending of underscore until a non-space character is encountered.
public static String spacedWord(String currentString) {
final StringBuilder sb = new StringBuilder(currentString.length());
int underscoreLength = 0;
boolean hasFirstNonspaceChar = false;
for (int i = 0; i < currentString.length(); i++) {
char c = currentString.charAt(i);
// ignore leading space
if (c == ' ' && !hasFirstNonspaceChar) {
underscoreLength = 0;
continue;
}
if ( c == ' ') {
// delay the appending of underscore with a counter
underscoreLength++;
} else {
if (!hasFirstNonspaceChar) {
hasFirstNonspaceChar = true;
} else {
// increment the count of underscore needs to be prepended before next character
underscoreLength++;
}
prependUnderscore(sb, underscoreLength);
underscoreLength = 0; // reset the counter
sb.append(c);
}
}
return sb.toString();
}
private static void prependUnderscore(StringBuilder sb, int length) {
for (int i = 0 ; i < length ; i++) {
sb.append('_');
}
}
Test:
public static void main(String[] args) { String input;
SpaceWord sw = new SpaceWord();
input = "hi there";
System.out.println(sw.spacedWord(input));
input = " hi there";
System.out.println(sw.spacedWord(input));
input = " hi there";
System.out.println(sw.spacedWord(input));
input = "hi there ";
System.out.println(sw.spacedWord(input));
input = "hi there ";
System.out.println(sw.spacedWord(input));
}
Output:
h_i__t_h_e_r_e
h_i__t_h_e_r_e
h_i__t_h_e_r_e
h_i__t_h_e_r_e
h_i__t_h_e_r_e
Upvotes: 0
Reputation: 27
First of all, don't use string additions within loops; it pollutes the heap. Instead use a StringBuilder
:
public String spacedWord()
{
StringBuilder spacedString = new StringBuilder();
for(int i = 0, l = currentString.length(); i < l; i++) {
if (i > 0)
spacedString.append('_');
spacedString.append(currentString.charAt(i));
}
return spacedString.toString();
}
Upvotes: 0
Reputation: 425318
You can use regex for a one-liner:
public static String spacedWord() {
return currentString.replaceAll("(?<=\\S) *(?=\\S)", "_");
}
This works by replacing all places in the string that are between non-space characters =, optionally including any spaces, with an underscore.
This expression (?<=\\S)
is a lookbehind (an assertion) for any non-space character while this expression (?=\\S)
is a lookahead (an assertion) for any non-space character.
Upvotes: 0
Reputation: 6266
"... I'm not sure how make sure an underscore doesn't appear at the end of the string. ..."
Skip the first index, and prepend the underscore.
String spacedString = "";
for (int i = 0; i<currentString.length(); i++)
{
if (i != 0) spacedString += "_";
spacedString += currentString.charAt(i);
}
return spacedString;
Alternately, use a StringBuilder to insert the char. Iterate backwards, to avoid the increasing length.
StringBuilder s = new StringBuilder(currentString);
for (int i = s.length() - 1; i > 0; i--) s.insert(i, '_');
Or, utilize a for-loop and the String#toCharArray method.
String spacedString = "";
int i = 0;
for (char c : currentString.toCharArray())
{
if (i++ != 0) spacedString += '_';
spacedString += c;
}
return spacedString;
Or, use a stream, and the String#join method.
String spacedString
= String.join("_", currentString.chars()
.mapToObj(x -> String.valueOf((char) x))
.toList());
Output
h_i_ _t_h_e_r_e
Upvotes: 0
Reputation: 111
The "-1" trick.
String spacedString = "";
String currentString= "Hello Peaple";
for (int i = 0; i<currentString.length()-1; i++)
{
spacedString = spacedString+currentString.charAt(i)+"_";
}
spacedString = spacedString+currentString.charAt(currentString.length()-1);
return spacedString;
Upvotes: 0