View Category

Output a string to the console

Write the string "Hello World!" to STDOUT
java
System.out.println("Hello World!");
System.out.printf("Hello World!\n");

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
java
Map<String, String> params = new HashMap<String, String>();
params.put("mode", "view");
params.put("fname", "Ron & Jean");
params.put("lname", "Smith");

StringBuilder buffer = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
buffer.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
System.out.println(buffer.toString());

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
java
public class SolutionXX {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
String words = "The quick brown fox jumps over the lazy dog. ";

for (int i = 0; i < 10; i++)
{
builder.append(words);
}

String toWrap = builder.toString();
int width = 76;
while (toWrap!=null && toWrap.length()>0)
{
String first = toWrap.length() > width ? toWrap.substring(0, width+1) : toWrap;
toWrap = (!toWrap.equals(first)) ? toWrap.substring(width + 1).trim() : null;
System.out.println("> " + first);
}

}
}
public class PangramWrapper {
public static void main(String[] args) {
int lineLimit = 78;
String newLine = "\n> ";
String pangram = "The quick brown fox jumps over the lazy dog. ";
String repeated = new String(new char[10]).replace("\0", pangram);

StringBuffer all = new StringBuffer(newLine + repeated);
for(int count = 1; count*lineLimit < all.length(); count++) {
all.insert(count * lineLimit, newLine);
}
System.out.println(all);
}
}
public class PangramWrapperViaRegexAndJoin {
public static void main(String[] args) {
String newLine = "\n> ",
pangram = "The quick brown fox jumps over the lazy dog. ",
repeated = new String(new char[10]).replace("\0", pangram);

final String[] splitted = repeated.split("(?<=\\G.{78})"); // worse performance than substring in for-loop
System.out.println("> "+ String.join(newLine, Arrays.asList(splitted)));
}
}

Define a string containing special characters

Define the literal string "\#{'}${"}/"
java
String special = "\\#{'}${\"}/";

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
java
String text = "This\nIs\nA\nMultiline\nString";
String text =
"This\n" +
"Is\n" +
"A\n" +
"Multiline\n" +
"String"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
java
System.out.println(a + "+" + b + "=" + (a+b));
System.out.printf("%d+%d=%d\n", a, b, a + b);

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
java
String reverse = new StringBuffer("reverse me").reverse().toString();
String reverse = new StringBuilder("reverse me").reverse().toString();
String reverse = StringUtils.reverse("reverse me");

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
java
List list = new ArrayList();
StringTokenizer st = new StringTokenizer(text, " ");
while(st.hasMoreTokens()) {
list.add(0, st.nextToken());
}
StringBuffer sb = new StringBuffer();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
String word = (String) iterator.next();
sb.append(word);
if (iterator.hasNext()) {
sb.append(" ");
}
}
String reversed = sb.toString();
List<String> ls = Arrays.asList("This is the end, my only friend!".split("\\s"));
Collections.reverse(ls);
StringBuilder sb = new StringBuilder(32); for (String s : ls) sb.append(" ").append(s);
String reversed = sb.toString().trim();
String reversed = StringUtils.reverseDelimited("This is the end, my only friend!", ' ');

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
java
String prefix = "> "; String input = "The quick brown fox jumps over the lazy dog.";

String[] lines = WordUtils.wrap(StringUtils.repeat(input, 10), 72 - prefix.length()).split("\n");

for (String line : lines) System.out.printf("%s%s\n", prefix, line);

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
java
String s = " hello "; String trimmed = s.trim();

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
java
CharArrayWriter rot13 = new CharArrayWriter() ;
for (char c : i ) {
char lc = Character.toLowerCase(c) ;
rot13.append( c += ( (lc >= 'a' && lc <= 'm') ? 13 : ( (lc >= 'n' && lc <= 'z') ? -13 : 0 ) )) ;
}

CharArrayWriter rot47 = new CharArrayWriter() ;
for (char c : i )
rot47.append( c += ( (c >= '!' && c <= 'O') ? 47 : ( (c >= 'P' && c <= '~') ? -47 : 0 ) )) ;

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
java
String upper = text.toUpperCase();

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
java
"Caps ARE overRated".toLowerCase();

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
java
String input = "man OF stEEL";
StringTokenizer tokenizer = new StringTokenizer(input);
StringBuffer sb = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
sb.append(' ');
}
String text = sb.toString();
StringBuilder sb = new StringBuilder("man OF stEEL"); String s = sb.toString();
int last = s.length() - 1;

for (int i = 0; i <= last; ++i)
if (Character.isSpaceChar(s.charAt(i)) && i < last) { ++i; sb.setCharAt(i, Character.toUpperCase(s.charAt(i))); }
else if (i == 0) sb.setCharAt(i, Character.toUpperCase(s.charAt(i)));
else sb.setCharAt(i, Character.toLowerCase(s.charAt(i)));
Matcher m = Pattern.compile("(\\w+)").matcher("man OF stEEL"); StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group().toLowerCase()); rsb.setCharAt(0, Character.toUpperCase(rsb.charAt(0)));
m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);
String text = WordUtils.capitalizeFully("man OF stEEL");