I'm creating a game of hangman, and long story short, is there a shortcut of sorts to put this array of separate strings together into a string other than doing like below?
String after = under[0] + under[1] + under[2] + under[3] + under[4] + under[5] + under[6] + under[7] + under[8] + under[9] + under[10] + under[11] + under[12] + under[13] + under[14] + under[15] + under[16] + under[17] + under[18] + under[19] + under[20] + under[21];
You can do it with a loop, like this:
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i != 22 ; i++) {
sb.append(under[i]);
}
String after = sb.toString();
You can also add strings to an initially empty string, but that's suboptimal, because all the intermediate strings get allocated and released in a loop.
Always use loop to perform repetitive operation like this.
Also, It is advised to use StringBuilder instead of String. String in JAVA is immutable.
StringBuilder sb = new StringBuilder();
int nCount = 22;
for (int iCnt = 0 ; iCnt <= nCount ; iCnt++) {
sb.append(under[iCnt]);
}
String after = sb.toString();
try it:
String after = "";
for (int i=0; i<22; i++)
after += under[i];
This code is not shorter, but is less tedious:
StringBuilder afterBldr = new StringBuilder();
for (String underEl : under) {
afterBldr.append(underEl);
}
String after = afterBldr.toString();
Apache Joiner can be used here.
Joiner.on("").join(names)
If you have access to the Apache Commons library, use the join() method, it's the nicest solution:
String str = StringUtils.join(under, "");
Related
I need to remove all white character from a string and I am not able to do so.
Anyone has an idea on how to do it?
Here is my string retrieved from an excel file via jxl API :
"Destination à gauche"
And here are its bytes :
6810111511610511097116105111110-96-32321039711799104101
There is the code I use to remove whitespaces :
public static void checkEntetes(Workbook book) {
String sheetName = "mysheet";
System.out.print(sheetName + " : ");
for(int i = 0; i < getColumnMax(book.getSheet(sheetName)); i++) {
String elementTrouve = book.getSheet(sheetName).getCell(i, 0).getContents();
String fileEntete = new String(elementTrouve.getBytes()).replaceAll("\\s+","");
System.out.println("\t" + elementTrouve + ", " + bytesArrayToString(elementTrouve.getBytes()));
System.out.println("\t" + fileEntete + ", " + bytesArrayToString(fileEntete.getBytes()));
}
System.out.println();
}
And this outputs :
"Destination à gauche", 6810111511610511097116105111110-96-32321039711799104101
"Destination àgauche", 6810111511610511097116105111110-96-321039711799104101
I even tried to make it myself and it still leaves a space before the 'à' char.
public static String removeWhiteChars(String s) {
String retour = "";
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c != (char) ' ') {
retour += c;
}
}
return retour;
}
regular expressions to the rescue:
str = str.replaceAll("\\s+", "")
will remove any sequence of whitespace characters. for example:
String input = "Destination à gauche";
String output = input.replaceAll("\\s+","");
System.out.println("output is \""+output+"\"");
outputs Destinationàgauche
if youre starting point is indeed the raw bytes (byte[]) you will first need to make them into a String:
byte[] inputData = //get from somewhere
String stringBefore = new String(inputData, Charset.forName("UTF-8")); //you need to know the encoding
String withoutSpaces = stringBefore.replaceAll("\\s+","");
byte[] outputData = withoutSpaces.getBytes(Charset.forName("UTF-8"));
If you would like to use a formula, the TRIM function will do exactly what you're looking for:
+----+------------+---------------------+
| | A | B |
+----+------------+---------------------+
| 1 | =TRIM(B1) | value to trim here |
+----+------------+---------------------+
So to do the whole column.
1) Insert a column
2) Insert TRIM function pointed at cell you are trying to correct.
3) Copy formula down the page
4) Copy inserted column
5) Paste as "Values"
Reference: Question number 9578397 on stackoverflow.com
Imagine this array.
data[0] = Marine
data[1] = Medic
data[2] = Firebat
I want to bring attribute of code (002530, 068270, 053800) to code[] array.
and pure text (Marine, Medic, Firebat).
Like this:
code[0] = 002530
code[1] = 068270
code[2] = 053800
text[0] = Marine
text[1] = Medic
text[2] = Firebat
How can I do that? Should I have to use StringTokenizer? or split()?
I don't know how to get that. Please Help me. Thank you.
You can use regular expressions, See this Voguella tutorial
".*code=([0-9]*).*>([A-Za-z]*)<.*"
And a code like this:
String[] array = new String[3];
array[0] = "Marine";
array[1] = "Medic";
array[2] = "Firebat";
Pattern pattern = Pattern.compile(".*code=([0-9]*).*>([A-Za-z]*)<.*");
for (int i = 0; i < array.length; i++) {
String string = array[i];
Matcher ma = pattern.matcher(string);
System.out.println("Code " + i + ":" + ma.replaceFirst("$1"));
System.out.println("Text " + i + ":" + ma.replaceFirst("$2"));
}
see a working example in: http://ideone.com/WJIjM5
Obs: remember to escape " in your strings.
I hava a List<String> that I need to serialize or make a String representation.
For example I have:
myList.add("Bob");
myList.add("account");
myList.add("userId");
The list can contain variable number of items and I need it to be serialized in this form:
\Bob\-\account\-\userId\
I can do a for loop like:
String ss;
for (String s: myList) {
s = "\\" + s + "\\";
ss = s + "-";
}
However there will be a "-" in the tail of the resulting String ss
Or is there a Google Guava function to do this already?
Using Guava:
String s = Joiner.on('-').join(Iterables.transform(list, new Function<String, String>() {
#Override
public String apply(String input) {
return "\\" + input + "\\";
}
});
The straight-forward way to solve this using Guava is the Joiner:
System.out.println("\\" + Joiner.on("\\-\\").join(myList) + "\\");
You can easily use Apaches Commons StringUtils:
String ss = "\\" + StringUtils.join(myList.iterator(), "\\-\\") + "\\";
Firstly, it is recommended to use StringBuilder during such concatenations.
Secondly, you can use Apache Common Lang's StringUtils.join()` method as follows to achieve the same:
ss = "\\" + StringUtils.join(myList.iterator(), "\\-\\") + "\\";
You can fix it by changing your loop like:
String ss = "";
for (String s: myList) {
s = "\\" + s + "\\";
if(ss.equals("")) {
ss = s;
}
else {
ss += " - " + s;
}
}
Perhaps the other solutions is an old fashioned for loop which is based on the List size().
The other thing I would do is use a StringBuffer as it is more efficient than concatenating Strings. Internally when you concatenate a String, the object is destroyed and recreated.
int myListSize = myList.size();
StringBuffer ss = new StringBuffer(4);
for (int i=0; i < myListSize; i++) {
ss.append("\\").append(myList.get(i)).append("\\");
if (i < myListSize - 1) {
ss.append("-");
}
}
Then to output from a StringBuffer:
ss.toString();
Personally I think these for loops (as above) end up being easier to read.
The simplest code for string joining that I know goes like this:
String sep = "", out = "";
for (String s : myList) {
out += sep + '\\' + s + '\\';
sep = "-";
}
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = reg.exec(text);
for (int i = 0; i < matchResult.getGroupCount(); i++) {
System.out.println("group" + i + "=" + matchResult.getGroup(i));
}
I am trying to get all blocks which are encapsulated by squared bracets form a path string:
and I only get group0="[build]" what i want is:
1:"[build]" 2:"[something]" 3:"[build]"
EDIT:
just to be clear words inside the brackets are generated with random text
public static String genText()
{
final int LENGTH = (int)(Math.random()*12)+4;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random() * 26) + 97));
}
String str = sb.toString();
str = str.substring(0,1).toUpperCase() + str.substring(1);
return str;
}
EDIT 2:
JDK works fine, GWT RegExp gives this problem
SOLVED:
Answer from Didier L
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String result = "";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = null;
while((matchResult=reg.exec(text)) != null){
if(matchResult.getGroupCount()==1)
System.out.println( matchResult.getGroup(0));
}
I don't know which regex library you are using but using the one from the JDK it would go along the lines of
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
Pattern pat = Pattern.compile(linkPattern);
Matcher mat = pat.matcher(text);
while (mat.find()) {
System.out.println(mat.group());
}
Output:
[build]
[something]
[build]
Try:
String linkPattern = "(\\[[A-Za-z_0-9]+\\])*";
EDIT:
Second try:
String linkPattern = "\\[(\\w+)\\]+"
Third try, see http://rubular.com/r/eyAQ3Vg68N
I want to achieve following using Regular expression in Java
String[] paramsToReplace = {"email", "address", "phone"};
//input URL string
String ip = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
//output URL string
String op = "http://www.google.com?name=bob&email=&address=&phone=";
The URL can contain special characters like %
Try this expression: (email=)[^&]+ (replace email with your array elements) and replace with the group: input.replaceAll("("+ paramsToReplace[i] + "=)[^&]+", "$1");
String input = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
String output = input;
for( String param : paramsToReplace ) {
output = output.replaceAll("("+ param + "=)[^&]+", "$1");
}
For the example above. you can use split
String[] temp = ip.split("?name=")[1].split("&")[0];
op = temp[0] + "?name=" + temp[1].split("&")[0] +"&email=&address=&phone=";
Something like this?
private final static String REPLACE_REGEX = "=.+\\&";
ip=ip+"&";
for(String param : paramsToReplace) {
ip = ip.replaceAll(param+REPLACE_REGEX, Matcher.quoteReplacement(param+"=&"));
}
P.S. This is only a concept, i didn't compile this code.
You don't need regular expressions to achieve that:
String op = ip;
for (String param : paramsToReplace) {
int start = op.indexOf("?" + param);
if (start < 0)
start = op.indexOf("&" + param);
if (start < 0)
continue;
int end = op.indexOf("&", start + 1);
if (end < 0)
end = op.length();
op = op.substring(0, start + param.length() + 2) + op.substring(end);
}