This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String Functions how to count delimiter in string line
I have a string as str = "one$two$three$four!five#six$" now how to count Total number of "$" in that string using java code.
Using replaceAll:
String str = "one$two$three$four!five#six$";
int count = str.length() - str.replaceAll("\\$","").length();
System.out.println("Done:"+ count);
Prints:
Done:4
Using replace instead of replaceAll would be less resource intensive. I just showed it to you with replaceAll because it can search for regex patterns, and that's what I use it for the most.
Note: using replaceAll I need to escape $, but with replace there is no such need:
str.replace("$");
str.replaceAll("\\$");
You can just iterate over the Characters in the string:
String str = "one$two$three$four!five#six$";
int counter = 0;
for (Character c: str.toCharArray()) {
if (c.equals('$')) {
counter++;
}
}
String s1 = "one$two$three$four!five#six$";
String s2 = s1.replace("$", "");
int result = s1.length() - s2.length();
Related
This question already has answers here:
Split string based on regex but keep delimiters
(3 answers)
Closed 4 years ago.
I know the split can be done with split functionality of java. I did that like in the below code
String[] sArr = name.split("[\\s.]+");
String newStr = "";
for (int i = 0; i < sArr.length; i++){
newStr = newStr + " " + mymethod(sArr[i]);
}
What i actually want to do is all the words in the string must pass through mymethod and reform the string. But on reforming i dont want to loss the dots and spaces which is actually there. For example Mr. John will remove the dot after reforming and would change in to Mr John which i don't want. So how to reform my string without losing anything in that actual string, but also each word to pass through mymethod also. Thanks in advance!
Iterate over String using any loop char by char and find for . and space char, Then by using substring() method split Original string by storing index.
Code:-
List<String> arr=new ArrayList<String>(); // Array to hold splitted tokens
String str="Mr. John abc. def";
int strt=0;
int end=0;
for (int i = 0; i < str.length(); i++) { //Iterate over Original String
if (str.charAt(i)=='.') // Match . character
{
end=i;
arr.add(str.substring(strt,end));
arr.add(str.charAt(i)+"");
strt=i+1;
}
if (str.charAt(i)==' ') // Match space character
{
end=i;
if (strt!=end) // check if space is not just after . character
arr.add(str.substring(strt,end));
strt=i+1;
}
}
System.out.println(arr);
This question already has answers here:
What is the most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff")?
(11 answers)
Closed 5 years ago.
I have a String nba-west-teams blazers and I want to convert the string into a format like nbaWestTeams blazers. Essentially, I want to remove all the dashes and replace the characters after the dash with it's uppercase equivalent.
I know I can use the String method replaceAll to remove all the dashes, but how do I get the character after the dash and uppercase it?
// Input
String withDashes = "nba-west-teams blazers"
String removeDashes = withDashes.replaceAll(....?)
// Expected conversion
String withoutDashes = "nbaWestTeams blazers"
Check out the indexOf and the replace method of the StringBuilder class. StringBuilder allows fast editing of Strings.
When you are finished use toString.
If you need more help just make a comment.
You can use Patterns with regex like this \-([a-z]):
String str = "nba-west-teams blazers";
String regex = "\\-([a-z])";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
str = str.replaceFirst(matcher.group(), matcher.group(1).toUpperCase());
}
System.out.println(str);//Output = nbaWestTeams blazers
So it will matche the first alphabets after the dash and replace the matched with the upper alphabets
You can iterate through the string and when a hyphen is found, just skip the hyphen and transform the next character to uppercase. You can use a StringBuilder to store the partial results as follows:
public static String toCamelCase(String str) {
// if the last char is '-', lets set the length to length - 1 to avoid out of bounds
final int len = str.charAt(str.length() - 1) == '-' ? str.length() - 1 : str.length();
StringBuilder builder = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (c == '-') {
++i;
builder.append(Character.toUpperCase(str.charAt(i)));
} else {
builder.append(c);
}
}
return builder.toString();
}
You can split the string at the space and use https://github.com/google/guava/wiki/StringsExplained#caseformat to convert the dashed substring into a camel cased string.
This question already has answers here:
Java: Simplest way to get last word in a string
(7 answers)
Closed 2 years ago.
how to remove last word in a string
word should be dynamic
for example:-String [] a={"100-muni-abc"};
i want output like this 100-muni
remove last one-abe
Try:
String a = "100-muni-abc";
String res = a.substring(0, a.lastIndexOf("-"));
Starting from
String str = "100-muni-abc";
Removing the last char
str = str.substring(0,str.length() - 1)
Removing the last 3 chars
str = str.substring(0,str.length() - 3)
A bit late huh?
Try this
String str = "100-muni-abc";
String [] parts = str.split("-");
System.out.println(parts[0]+"-"+parts[1]);
Try this
String text = What is the name of your first love?;
String lastWord = text.substring(text.lastIndexOf(" ")+1);
System.out.println(lastWord);
Output Answer : love?
This question already has answers here:
Replace the last part of a string
(11 answers)
Closed 8 years ago.
Let's say I have a string
string myWord="AAAAA";
I want to replace "AA" with "BB", but only the last occurrence, like so:
"AAABB"
Neither string.replace() nor string.replaceFirst() would do the job.
Is there a string.replaceLast()? And, If not, will there ever be one or is there an alternative also working with regexes?
Find the index of the last occurrence of the substring.
String myWord = "AAAAAasdas";
String toReplace = "AA";
String replacement = "BBB";
int start = myWord.lastIndexOf(toReplace);
Create a StringBuilder (you can just concatenate Strings if you wanted to).
StringBuilder builder = new StringBuilder();
Append the part before the last occurrence.
builder.append(myWord.substring(0, start));
Append the String you want to use as a replacement.
builder.append(replacement);
Append the part after the last occurrence from the original `String.
builder.append(myWord.substring(start + toReplace.length()));
And you're done.
System.out.println(builder);
You can do this:
myWord = myWord.replaceAll("AA$","BB");
$ means at the last.
Just get the last index and do an in place replacement of the expression with what you want to replace.
myWord is the original word sayAABDCAADEF. sourceWord is what you want to replace, say AA
targetWord is what you want to replace it with say BB.
StringBuilder strb=new StringBuilder(myWord);
int index=strb.lastIndexOf(sourceWord);
strb.replace(index,sourceWord.length()+index,targetWord);
return strb.toString();
This is useful when you want to just replace strings with Strings.A better way to do it is to use Pattern matcher and find the last matching index. Take as substring from that index, use the replace function there and then add it back to the original String. This will help you to replace regular expressions as well
String string = "AAAAA";
String reverse = new StringBuffer(string).reverse().toString();
reverse = reverse.replaceFirst(...) // you need to reverse needle and replacement string aswell!
string = new StringBuffer(reverse).reverse().toString();
It seems like there could be a regex answer to this.
I initially was trying to solve this through regex, but could not solve for situations like 'AAAzzA'.
So I came up with this answer below, which can handle both 'AAAAA' and 'AAAzzA'. This may not be the best answer, but I guess it works.
The basic idea is to find the last index of 'AA' occurrence and split string by that index:
String myWord = "AAAAAzzA";
String source = "AA";
String target = "BB";
int lastIndex = -1;
if ((lastIndex = myWord.lastIndexOf(source)) >= 0) {
String f = myWord.substring(0, lastIndex);
String b = myWord.substring(lastIndex + target.length() >= myWord
.length() ? myWord.length() : lastIndex + target.length(),
myWord.length());
myWord = f + target + b;
}
System.out.println(myWord);
myWord=myWord.replaceAll("AA(?!A)","BB");
You can do this with String#subtring
myWord= myWord.substring(0, myWord.length() - 2) + "BB";
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a long string. What is the regular expression to split the numbers into the array?
Are you removing or splitting? This will remove all the non-numeric characters.
myStr = myStr.replaceAll( "[^\\d]", "" )
One more approach for removing all non-numeric characters from a string:
String newString = oldString.replaceAll("[^0-9]", "");
String str= "somestring";
String[] values = str.split("\\D+");
Another regex solution:
string.replace(/\D/g,''); //remove the non-Numeric
Similarly, you can
string.replace(/\W/g,''); //remove the non-alphaNumeric
In RegEX, the symbol '\' would make the letter following it a template: \w -- alphanumeric, and \W - Non-AlphaNumeric, negates when you capitalize the letter.
You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.
myString.split("\\D+");
Java 8 collection streams :
StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());
This works in Flex SDK 4.14.0
myString.replace(/[^0-9&&^.]/g, "");
you could use a recursive method like below:
public static String getAllNumbersFromString(String input) {
if (input == null || input.length() == 0) {
return "";
}
char c = input.charAt(input.length() - 1);
String newinput = input.substring(0, input.length() - 1);
if (c >= '0' && c<= '9') {
return getAllNumbersFromString(newinput) + c;
} else {
return getAllNumbersFromString(newinput);
}
}
Previous answers will strip your decimal point. If you want to save your decimal, you might want to
String str = "My values are : 900.00, 700.00, 650.50";
String[] values = str.split("[^\\d.?\\d]");
// split on wherever they are not digits except the '.' decimal point
// values: { "900.00", "700.00", "650.50"}
Simple way without using Regex:
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}