Reverse string without changing the position of special character using regex - java

class der{
public static void maxLength(String str) {
String s = " ";
s = str.replaceAll("[^a-z]+", " ");
String rev = " ";
char ch[] = s.toCharArray();
for(int i =ch.length-1; i>=0 ; i--){
rev = rev + ch[i];
}
System.out.println(rev);
}
public static void main(String[] args){
String str = "a#utom!at$ion#";
maxLength(str);
}
}
I tried the above with regex function where i first tried to remove special character and then reverse the string. But is there any option to add special character back again to the reverse strings?
My o/p for the current code is this noi ta motu a so in blank space i want to put the special character again.

You may use this Java code:
String str = "a#utom!at$ion#";
// \W+ matches 1+ of any non-word characters
Matcher m = Pattern.compile("\\W+").matcher(str);
StringBuilder sb = new StringBuilder();
int start=0;
// loop through the matches of \W+
while (m.find()) {
// append reverse of substring before current match
// and then the match itself is appended in buffer
sb
.append(new StringBuilder(str.substring(start, m.start())).reverse())
.append(m.group());
start = m.end();
}
// append remaining part after last match in buffer
sb.append(new StringBuilder(str.substring(start)).reverse());
// print the results
System.out.println(sb);
Output:
a#motu!ta$noi#

Related

String convertion in java with inbuilt string function

How do i convert a string like below
String str="[in,us,eu,af,th]";
into
["in","us","eu","af","th"]
Just use String functions:
str = str.substring(1,str.length()-2); // remove brackets
String a[] = str.split(","); //split it.
String result = str.replace("[", "[\"").replace(",", "\",\"").replace("]", "\"]");
public static void main(String[] args) {
String str = "[in,us,eu,af,th]";
str = str.substring(1, str.length() - 1);
// #1 remove starting and ending brackets
System.out.println("String without brackets : " + str);
//#2 split by comma
String[] stringTokens = str.split(",");
StringBuffer outputStrBuffer = new StringBuffer();
outputStrBuffer.append("["); // append starting square bracket
for (int i = 0; i <= stringTokens.length - 1; i++) {
//prefix and postfix each token with double quote
outputStrBuffer.append("\"");
outputStrBuffer.append(stringTokens[i]);
outputStrBuffer.append("\"");
// for last toke dont append comma at end
if (i != stringTokens.length - 1) {
outputStrBuffer.append(",");
}
}
outputStrBuffer.append("]"); // append ending square bracket
System.out.println("String prefixed & postfixed with double quotes, separated by comma : " + outputStrBuffer.toString());
}

java string iterations of char variables

How do I move char characters to left or to right in a string?
Reading the input string backwards you need to keep every character on an odd index of each word and any blank characters.
You could start with this snippet. See it as a PoC to demonstrate the logic. Optimisations are possible.
String encoded = "bxoqb swi eymrawn yim";
StringBuilder decoded = new StringBuilder();
boolean keep = true;
for (int i = encoded.length() - 1; i >= 0; i--) {
if (encoded.charAt(i) != ' ') {
if (keep) {
decoded.append(encoded.charAt(i));
}
keep = !keep;
} else {
decoded.append(' ');
keep = true;
}
}
System.out.println("decoded = " + decoded);
output
decoded = my name is bob
explanation
the for-loop processes the string backwards, so the characters are processed as miy nwarmye iws bqoxb
the variable i hold the current index position in the string encoded
as we want to keep only the characters on odd positions in a word the variable keep is used as a indicator
when the variable keep is true we append the current character (the one on position i in string encoded) to the string buffer decoded
if the current processed character is not a the value of keepis negated (true->false, false->true), so we append characters on every odd position
as we need to keep between the words also we have to treat this separately, each is appended to decoded and keep is set to true so the next non-blank character would be added too
Try this:
StringBuilder builder = new StringBuilder();
String[] charArray = encoded.split(" ");
for(int i = charArray.length-1 ; i >= 0; i--){
builder.append(charArray[i]);
}
String decoded = builder.toString();
You have to use StringBuffer to reverse the sentence.Then you can split your sentence word by word using the spaces between the words. After that basic java knowledge ...
String ss = "bxoqb swi eymrawn yim";
StringBuilder buffer = new StringBuilder(ss);
String word[] = buffer.reverse().toString().split(" ");
for (String word1 : word) {
char c[]=word1.toCharArray();
for(int x=0;x<c.length;x++){
if(x%2==0){
System.out.print(c[x]);
}
}
System.out.print(" ");
}

Remove characters at certain position at string

I want to remove certain characters at specific positions of the String. I have the positions, but I am facing problems removing the characters.
what i am doing is:
if (string.subSequence(k, k + 4).equals("\n\t\t\t")){
string = string.subSequence(0, k) + "" + s.subSequence(k, s.length());
}
I need to remove "\n\t\t\t" from string
Use StringBuilder:
StringBuilder sb = new StringBuilder(str);
sb.delete(start, end);
sb.deleteCharAt(index);
String result = sb.toString();
Use StringBuilder
String str=" ab a acd";
StringBuilder sb = new StringBuilder(str);
sb.delete(0,3);
sb.deleteCharAt(0);
String result = sb.toString();
System.out.println(result);
public static String remove(int postion, String stringName) {
char [] charArray = stringName.toCharArray();
char [] resultArray = new char[charArray.length];
int count = 0;
for (int i=0; i< charArray.length; i++) {
if (i != postion-1) {
resultArray[count] = charArray[i];
count++;
}
}
return String.valueOf(resultArray);
}
Use String.ReplaceAll() instead of this.
But if you only want to remove specific element only you can use substring().
Now you want to know position which you already know.
Put your points in a HashSet called set
StringBuilder sb=new StringBuilder();
for(int i=0;i<string.length();i++){
if(!set.contains(string.charAt(i)))
sb.append(string.charAt(i));
}
String reformattedString=sb.toString();
First you have to put \ in front of the special characters in order to do the matching of the two string, thus you will have .equals("\"\\n\\t\\t\\t\""), otherwise the substring is not going to be recognized inside the string. Then the other thing which you have to fix is the position of the index begin and end inside .subSequence(k,k+10) since the first and the last character are 10 positions apart and not 4. Note also that when you patch the string you go from position 0 to k and from k+10 to str.length(). If you go from 0 --> k and k --> length() you just join the old string together :).
Your code should work like this, I have tested it already
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length()));
}
also you don't need +" "+ since you are adding strings. Whoever wants to see the effect of this can run this simple code:
public class ReplaceChars_20354310_part2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String str = "This is a weird string containg balndbfhr frfrf br brbfbrf b\"\\n\\t\\t\\t\"";
System.out.println(str); //print str
System.out.println(ReplaceChars(str)); //then print after you replace the substring
System.out.println("\n"); //skip line
String str2 = "Whatever\"\\n\\t\\t\\t\"you want to put here"; //print str
System.out.println(str2); //then print after you replace the substring
System.out.println(ReplaceChars(str2));
}
//Method ReplaceChars
public static String ReplaceChars (String str) {
String newstr ="";
int k;
k = str.indexOf("\"\\n\\t\\t\\t\""); //position were the string starts within the larger string
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length())); //or just str
}
return newstr;
}//end method
}

How to Split a string in java based on limit

I have following String and i want to split this string into number of sub strings(by taking ',' as a delimeter) when its length reaches 36. Its not exactly splitting on 36'th position
String message = "This is some(sampletext), and has to be splited properly";
I want to get the output as two substrings follows:
1. 'This is some (sampletext)'
2. 'and has to be splited properly'
Thanks in advance.
A solution based on regex:
String s = "This is some sample text and has to be splited properly";
Pattern splitPattern = Pattern.compile(".{1,15}\\b");
Matcher m = splitPattern.matcher(s);
List<String> stringList = new ArrayList<String>();
while (m.find()) {
stringList.add(m.group(0).trim());
}
Update:
trim() can be droped by changing the pattern to end in space or end of string:
String s = "This is some sample text and has to be splited properly";
Pattern splitPattern = Pattern.compile("(.{1,15})\\b( |$)");
Matcher m = splitPattern.matcher(s);
List<String> stringList = new ArrayList<String>();
while (m.find()) {
stringList.add(m.group(1));
}
group(1) means that I only need the first part of the pattern (.{1,15}) as output.
.{1,15} - a sequence of any characters (".") with any length between 1 and 15 ({1,15})
\b - a word break (a non-character before of after any word)
( |$) - space or end of string
In addition I've added () surrounding .{1,15} so I can use it as a whole group (m.group(1)).
Depending on the desired result, this expression can be tweaked.
Update:
If you want to split message by comma only if it's length would be over 36, try the following expression:
Pattern splitPattern = Pattern.compile("(.{1,36})\\b(,|$)");
The best solution I can think of is to make a function that iterates through the string. In the function you could keep track of whitespace characters, and for each 16th position you could add a substring to a list based on the position of the last encountered whitespace. After it has found a substring, you start anew from the last encountered whitespace. Then you simply return the list of substrings.
Here's a tidy answer:
String message = "This is some sample text and has to be splited properly";
String[] temp = message.split("(?<=^.{1,16}) ");
String part1 = message.substring(0, message.length() - temp[temp.length - 1].length() - 1);
String part2 = message.substring(message.length() - temp[temp.length - 1].length());
This should work on all inputs, except when there are sequences of chars without whitespace longer than 16. It also creates the minimum amount of extra Strings by indexing into the original one.
public static void main(String[] args) throws IOException
{
String message = "This is some sample text and has to be splited properly";
List<String> result = new ArrayList<String>();
int start = 0;
while (start + 16 < message.length())
{
int end = start + 16;
while (!Character.isWhitespace(message.charAt(end--)));
result.add(message.substring(start, end + 1));
start = end + 2;
}
result.add(message.substring(start));
System.out.println(result);
}
If you have a simple text as the one you showed above (words separated by blank spaces) you can always think of StringTokenizer. Here's some simple code working for your case:
public static void main(String[] args) {
String message = "This is some sample text and has to be splited properly";
while (message.length() > 0) {
String token = "";
StringTokenizer st = new StringTokenizer(message);
while (st.hasMoreTokens()) {
String nt = st.nextToken();
String foo = "";
if (token.length()==0) {
foo = nt;
}
else {
foo = token + " " + nt;
}
if (foo.length() < 16)
token = foo;
else {
System.out.print("'" + token + "' ");
message = message.substring(token.length() + 1, message.length());
break;
}
if (!st.hasMoreTokens()) {
System.out.print("'" + token + "' ");
message = message.substring(token.length(), message.length());
}
}
}
}

Breaking Strings into chars that are in upper case

I'm making a method to read a whole class code and do some stuff with it.
What I want to do is get the name of the method, and make a String with it.
Something like removeProduct
I'll make a String "Remove Product"
How can I split the name method in capital cases?
How can I build this new string with the first letter of each word as capital case?
I'm doing it with substring, is there a easier and better way to do it?
ps: I'm sure my brazilian English didn't help on title. If anyone can make it looks better, I'd appreciate.
Don't bother reinvent the wheel, use the method in commons-lang
String input = "methodName";
String[] words = StringUtils.splitByCharacterTypeCamelCase(methodName);
String humanised = StringUtils.join(words, ' ');
You can use a regular expression to split the name into the various words, and then capitalize the first one:
public static void main(String[] args) {
String input = "removeProduct";
//split into words
String[] words = input.split("(?=[A-Z])");
words[0] = capitalizeFirstLetter(words[0]);
//join
StringBuilder builder = new StringBuilder();
for ( String s : words ) {
builder.append(s).append(" ");
}
System.out.println(builder.toString());
}
private static String capitalizeFirstLetter(String in) {
return in.substring(0, 1).toUpperCase() + in.substring(1);
}
Note that this needs better corner case handling, such as not appending a space at the end and handling 1-char words.
Edit: I meant to explain the regex. The regular expression (?=[A-Z]) is a zero-width assertion (positive lookahead) matching a position where the next character is between 'A' and 'Z'.
You can do this in 2 steps:
1 - Make the first letter of the string uppercase.
2 - Insert an space before an uppercase letter which is preceded by a lowercase letter.
For step 1 you can use a function and for step 2 you can use String.replaceAll method:
String str = "removeProduct";
str = capitalizeFirst(str);
str = str.replaceAll("(?<=[^A-Z])([A-Z])"," $1");
static String capitalizeFirst(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
Code In Action
#MrWiggles is right.
Just one more way to do this without being fancy :)
import java.util.StringTokenizer;
public class StringUtil {
public static String captilizeFirstLetter(String token) {
return Character.toUpperCase(token.charAt(0)) + token.substring(1);
}
public static String convert(String str) {
final StringTokenizer st = new StringTokenizer(str,
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z", true);
final StringBuilder sb = new StringBuilder();
String token;
if (st.hasMoreTokens()) {
token = st.nextToken();
sb.append(StringUtil.captilizeFirstLetter(token) + " ");
}
while (st.hasMoreTokens()) {
token = st.nextToken();
if (st.hasMoreTokens()) {
token = token + st.nextToken();
}
sb.append(StringUtil.captilizeFirstLetter(token) + " ");
}
return sb.toString().trim();
}
public static void main(String[] args) throws Exception {
String words = StringUtil.convert("helloWorldHowAreYou");
System.out.println(words);
}
}
public String convertMethodName(String methodName) {
StringBuilder sb = new StringBuilder().append(Character.toUpperCase(methodName.charAt(0)));
for (int i = 1; i < methodName.length(); i++) {
char c = methodName.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(' ');
}
sb.append(c);
}
return sb.toString();
}
Handling it this way may give you some finer control in case you want to add in functionality later for other situations (multiple caps in a row, etc.). Basically, for each character, it just checks to see if it's within the bounds of capital letters (character codes 65-90, inclusive), and if so, adds a space to the buffer before the word begins.
EDIT: Using Character.isUpperCase()

Categories

Resources