I have String of format something like this
String VIA = "1.NEW DELHI 2. Lucknow 3. Agra";
I want to insert a newline character before every digit occurring succeeded a dot so that it final string is like this
String VIA = "1.NEW DELHI " +"\n"+"2. Lucknow " +"\n"+"3. Agra";
How can I do it. I read Stringbuilder and String spilt, but now I am confused.
Something like:
StringBuilder builder = new StringBuilder();
String[] splits = VIA.split("\d+\.+");
for(String split : splits){
builder.append(split).append("\n");
}
String output = builder.toString().trim();
The safest way here to do that would be go in a for loop and check if the char is a isDigit() and then adding a '\n' before adding it to the return String. Please note, I am not sure if you want to put a '\n' before the first digit.
String temp = "";
for(int i=0; i<VIA.length(); i++) {
if(Character.isDigit(VIA.charAt(i)))
temp += "\n" + VIA.charAt(i);
} else {
temp += VIA.charAt(i);
}
}
VIA = temp;
//just use i=1 here of you want to skip the first charachter or better do a boolean check for first digit.
Related
Im trying to rebuild a string using StringBuilder. I'm a little unsure of which method to use to get the "'," inserted back into the same place. In the code below I'm using the
"insert(int dstOffset, CharSequence s, int start, int end)" method. My code doesn't contain any errors however it doesn't run properly.
Please note I will also be escaping characters (i.e., =) in the string but I havent written that part of the code yet. Currently I'm trying to learn how to split the string and then rebuild it.
Thanks
public class StringTestProgram
{
public static void main(String[] args)
{
String relativeDN = "cn=abc,dn=xyz,ou=abc/def";
String[] stringData = relativeDN.split(",");
for (String stringoutput : stringData)
{
System.out.print(stringoutput);
StringBuilder sb = new StringBuilder(stringoutput);
CharSequence charAdded = ",";
sb.insert(6,charAdded,0,12);
System.out.print(sb.toString());
}
}
}
Revised code
public class StringTestProgram {
public static void main(String[] args) {
String relativeDN = "cn=abc,dn=xyz,ou=abc/def";
System.out.println(relativeDN);
//Split String
String[] stringData = relativeDN.split(",");
{
StringBuilder sb = new StringBuilder();
CharSequence charAdded = ",";
// loop thru each element of the array
for (int place = 0; place < stringData.length; place++) {
System.out.println(stringData[place]);
{
int eq = relativeDN.indexOf('=');
String sub = relativeDN.substring(0, eq);
System.out.println(sub);
}
// append element to the StringBuilder
sb.append(stringData[place]);
// avoids adding an extra ',' at the end
if (place < stringData.length - 1)
// if not at the last element, add the ',' character
sb.append(charAdded);
}
System.out.print(sb.toString());
}
}
}
Im new to stackoverflow and I'm not sure if its ok to ask this question in this thread or if I should create a seperate thread for this question. If possible please advise.
The code above now splits the string at the "," character. It also rebuilds the
string back to its original state. I would also like to use the indexof and .substring
methods to get the string value after the "=" sign. Currently my program only outputs
the first two characters of the initial string value before the "=" sign. Not sure where
in my code I'm making an error. Any help would be appreciated.
My Current Output
cn=abc,dn=xyz,ou=abc/def
cn=abc
cn
dn=xyz
cn
ou=abc/def
cn
cn=abc,dn=xyz,ou=abc/def
Desired Output
cn=abc,dn=xyz,ou=abc/def
cn=abc
abc
dn=xyz
xyz
ou=abc/def
abc/def
cn=abc,dn=xyz,ou=abc/def
The easiest way to do this pre Java 8 is to use 1 StringBuilder for all the elements and add Strings to the builder by using the append() method
StringBuilder builder = new StringBuilder();
for (String stringoutput : stringData) {
builder.append(stringoutput).append(',');
}
//have an extra trailing comma so remove it
//use length -1 as end coord because it's exclusive
String result = builder.substring(0, builder.length() -1);
If you are using Java 8 you can use the new Stream API and Collectors.joining()
String result = Arrays.stream(relativeDN.split(","))
.collect(Collectors.joining(","));
You're initializing sb every time you enter the loop, meaning that you're disposing of your StringBuilder every time you enter the loop and recreate it with only the next subtring.
Fixed:
String relativeDN = "cn=abc,dn=xyz,ou=abc/def";
String[] stringData = relativeDN.split(",");
StringBuilder sb = new StringBuilder();
CharSequence charAdded = ",";
for (String stringoutput : stringData) {
System.out.print(stringoutput);
sb.append(stringoutput).append(charAdded);
}
sb.setLength(sb.length() - 1);
System.out.print(sb.toString());
Try out this code
public class StringTestProgram {
public static void main(String[] args) {
String relativeDN = "cn=abc,dn=xyz,ou=abc/def";
String[] stringData = relativeDN.split(",");
StringBuilder sb = new StringBuilder();
CharSequence charAdded = ",";
for (int i = 0; i < stringData .length; i++) { //walk over each element of the array
System.out.println(stringData[i]);
sb.append(stringData[i]); // append element to the StringBuilder
if (i < stringData.length - 1) //avoids adding an extra ',' at the end
sb.append(charAdded); // if not at the last element, add the ',' character
}
System.out.print(sb.toString());
}
}
Here you will reconstruct the original string exactly as it was (i.e. without adding a trailing ','):
cn=abc,dn=xyz,ou=abc/def
UPDATE: In the for loop I just walk over every element of the array that stores the splitted String and append the elements to the StringBuilder instance one by one. After appending each element I check if we are currently at the last element of the array. If not, I append the ',' character.
Like this:
for (String stringoutput : stringData)
sb.append(stringoutput).append(',');
Fixed: Using this approach, you would have to remove the last ,
String result = sb.toString().substring(0,sb.toString().length()-1);
System.out.println(result);
I noticed in the other answers that there would be an extra comma at the end. You have to use a prefix variable and then change it in the loop so that there won't be an extra comma.
String relativeDN = "cn=abc,dn=xyz,ou=abc/def";
String[] stringData = relativeDN.split(",");
StringBuilder sb = new StringBuilder();
String prefix = "";
for (String element : stringData) {
sb.append(prefix);
prefix=",";
sb.append(element);
}
String output = sb.toString();
Inside the loop the prefix is appended, but on the first time through the loop the prefix is set to empty quotes so that there won't be a comma before the first element. Next prefix is changed to a comma so that in the next turn through the loop a comma will be added after the first element. Lastly, the element is added. This results in the correct output because the comma is added before the element, but only after the first iteration.
I want to split a string into multiple parts based on parentheses. So if I have the following string:
In fair (*NAME OF A CITY), where we lay our (*NOUN),
The string should be split as:
In fair
*NAME OF A CITY
, where we lay our
*NOUN
I set up a delimiter like so:
String delim = "[()]";
String [] inputWords = line.split (delim);
Because the strings in all caps with an * at the beginning are going to be replaced with user input, I set up a loop like so:
while (input.hasNextLine())
{
line = input.nextLine();
String [] inputWords = line.split (delim);
for (int i = 0; i < inputWords.length; i++)
{
if (inputWords[i].charAt(0) != '*')
{
newLine.append (inputWords[i]);
}
else
{
String userWord = JOptionPane.showInputDialog (null, inputWords[i].substring (1, inputWords[i].length()));
newLine.append (userWord);
}
}
output.println (newLine.toString());
output.flush();
newLine.delete (0, line.length());
}
Looks like I'm getting an error with this if statement:
if (inputWords[i].charAt(0) != '*')
When I run it, I get a StringIndexOutOfBoundsException: String index out of range: 0. Not sure why that's happening. Any advice? Thank you!
apparently line = input.nextLine(); gives you a blank string, as #Marco already mentioned.
handle empty line(s) before processing further.
I have a string like this:
"core/pages/viewemployee.jsff"
From this code, I need to get "viewemployee". How do I get this using Java?
Suppose that you have that string saved in a variable named myString.
String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));
But you need to make the same control before doing substring in this one, because if there aren't those characters you will get a "-1" from lastIndexOf(), or indexOf(), and it will break your substring invocation.
I suggest looking for the Javadoc documentation.
You can solve this with regex (given you only need a group of word characters between the last "/" and "."):
String str="core/pages/viewemployee.jsff";
str=str.replaceFirst(".*/(\\w+).*","$1");
System.out.println(str); //prints viewemployee
You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.
String myStr = "core/pages/viewemployee.bak.jsff";
String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");
String fileNameStr = "";
for(int i = 0; i < fileNameTokens.length - 1; i++) {
fileNameStr += fileNameTokens[i] + ".";
}
fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);
System.out.print(fileNameStr) //--> "viewemployee.bak"
These are file paths. Consider using File.getName(), especially if you already have the File object:
File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"
And to remove the extension:
String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"
With this we can handle strings like "../viewemployee.2.jsff".
The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..
The below will get you viewemployee.jsff:
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn = idx >= 0 ? fileName.substring(idx + 1) : fileName;
To remove the file Extension and get only viewemployee, similarly:
idx = fileNameWithExtn.lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn;
I am getting the names as String. How can I display in the following format: If it's single word, I need to display the first character alone. If it's two words, I need to display the first two characters of the word.
John : J
Peter: P
Mathew Rails : MR
Sergy Bein : SB
I cannot use an enum as I am not sure that the list would return the same values all the time. Though they said, it's never going to change.
String name = myString.split('');
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
String finalName = topTitle + finalName;
The above code fine, but its not working. I am not getting any exception either.
There are few mistakes in your attempted code.
String#split takes a String as regex.
Return value of String#split is an array of String.
so it should be:
String[] name = myString.split(" ");
or
String[] name = myString.split("\\s+);
You also need to check for # of elements in array first like this to avoid exception:
String topTitle, subTitle;
if (name.length == 2) {
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
}
else
topTitle = name.subString(0,1);
The String.split method split a string into an array of strings, based on your regular expression.
This should work:
String[] names = myString.split("\\s+");
String topTitle = names[0].subString(0,1);
String subTitle = names[1].subString(0,1);
String finalName = topTitle + finalName;
First: "name" should be an array.
String[] names = myString.split(" ");
Second: You should use an if function and the length variable to determine the length of a variable.
String initial = "";
if(names.length > 1){
initial = names[0].subString(0,1) + names[1].subString(0,1);
}else{
initial = names[0].subString(0,1);
}
Alternatively you could use a for loop
String initial = "";
for(int i = 0; i < names.length; i++){
initial += names[i].subString(0,1);
}
You were close..
String[] name = myString.split(" ");
String finalName = name[0].charAt(0)+""+(name.length==1?"":name[1].charAt(0));
(name.length==1?"":name[1].charAt(0)) is a ternary operator which would return empty string if length of name array is 1 else it would return 1st character
This will work for you
public static void getString(String str) throws IOException {
String[] strr=str.split(" ");
StringBuilder sb=new StringBuilder();
for(int i=0;i<strr.length;i++){
sb.append(strr[i].charAt(0));
}
System.out.println(sb);
}
It looks simple problem , but I'll apprisiate any help here :
I need to swap password value (can be any value) to "****"
The origunal sting is string resived from xml
The problem is that I getting as output only line:
<parameter><value>*****</value></parameter>
But I need the whole string as output only with password value replaced
Thank you in advance
String originalString = "<parameter>" +
"<name>password</name>"+
"<value>my123pass</value>"+
"</parameter>"+
"<parameter>"+
"<name>LoginAttempt</name>"+
"<value>1</value>"+
"</parameter>";
System.out.println("originalString: "+originalString);
Pattern pat = Pattern.compile("<name>password</name><value>.*</value>");
Matcher mat = pat.matcher(originalString);
System.out.println("NewString: ");
System.out.print(mat.replaceFirst("<value>***</value>"));
mat.reset();
If I'm not mistaken, you want to change the password in the string with *'s. You can do it by using String methods directly. Just get the last index of the starting value tag and iterate until you reach a "<", replacing the value between those two with *'s. Something like this:
int from = originalString.lastIndexOf("<name>password</name><value>");
bool endIteration = false;
for(i = from + 1 ; i < originalString.length() && !endIteration ; i ++) {
if(originalString.toCharArray()[i] == '<')
endIteration = true;
else {
originalString.toCharArray()[i] = '*';
}
}
EDIT: There is another way making a proper use of all the String class goodies:
int from = originalString.lastIndexOf("<name>password</name><value>");
int to = originalString.indexOf("</value>", from);
Arrays.fill(originalString.toCharArray(), from, to, '*');