I am replacing a character in a string. There has to be a better way to do this, right?
public static String eqEq(String stringIn) {
char[] stringArray;
stringArray = stringIn.toCharArray();
for (int i = 0; i < stringIn.length(); i++){
if(stringArray[i] == '='){
stringArray[i] = '?';
}
}
String sReturn = new String(stringArray);
return sReturn;
}
Something wrong with replace()?
public static String eqEq(String stringIn) {
return stringIn.replace('=', '?');
}
Note that replace() replaces all occurrences, but uses plain text search/replacements, unlike replaceAll() which is the regex version of replace().
Also note the replace() has two versions: One version that has char parameters (used here), and another that has String parameters in case you want to search/replace more than one character.
You could try String#replace, for example
stringIn = stringIn.replace('=', '?');
You could even use String#repalceAll if you want to use a regular expression instead.
You could even use a StringBuilder
StringBuilder sb = new StringBuilder(value);
int index = -1;
while ((index = sb.indexOf("=")) != -1) {
sb.replace(index, index + 1, "?");
}
The choice is yours
You can use the replace or replaceAll methods on the String class, as follows:
public static String eqEq(String stringIn) {
stringIn.replace("=", "?");
}
OR
public static String eqEq(String stringIn) {
stringIn.replaceAll("=", "?");
}
See a live example of this code running (using replaceAll) on a sample string.
Related
public static String removeLeadingZeroes(String value):
Given a valid, non-empty input, the method should return the input with all leading zeroes removed. Thus, if the input is “0003605”, the method should return “3605”. As a special case, when the input contains only zeroes (such as “000” or “0000000”), the method should return “0”
public class NumberSystemService {
/**
*
* Precondition: value is purely numeric
* #param value
* #return the value with leading zeroes removed.
* Should return "0" for input being "" or containing all zeroes
*/
public static String removeLeadingZeroes(String value) {
while (value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I don't know how to write codes for a string "0000".
If the string always contains a valid integer the return new Integer(value).toString(); is the easiest.
public static String removeLeadingZeroes(String value) {
return new Integer(value).toString();
}
Stop reinventing the wheel.
Almost no software development problem you ever encounter will be the first time it has been encountered;
instead,
it will only be the first time you encounter it.
Almost every utility method you will ever need has already been written by the Apache project and/or the guava project (or some similar that I have not encountered).
Read the Apache StringUtils JavaDoc page.
This utility is likely to already provide every string manipulation functionality you will ever need.
Some example code to solve your problem:
public String stripLeadingZeros(final String data)
{
final String strippedData;
strippedData = StringUtils.stripStart(data, "0");
return StringUtils.defaultString(strippedData, "0");
}
You could add a check on the string's length:
public static String removeLeadingZeroes(String value) {
while (value.length() > 1 && value.indexOf("0")==0)
value = value.substring(1);
return value;
}
I would consider checking for that case first. Loop through the string character by character checking for a non "0" character. If you see a non "0" character use the process you have. If you don't, return "0". Here's how I would do it (untested, but close)
boolean allZero = true;
for (int i=0;i<value.length() && allZero;i++)
{
if (value.charAt(i)!='0')
allZero = false;
}
if (allZero)
return "0"
...The code you already have
private String trimLeadingZeroes(inputStringWithZeroes){
final Integer trimZeroes = Integer.parseInt(inputStringWithZeroes);
return trimZeroes.toString();
}
You can use below replace function it will work on a string having both alphanumeric or numeric
s.replaceFirst("^0+(?!$)", "")
public String removeLeadingZeros(String digits) {
//String.format("%.0f", Double.parseDouble(digits)) //Alternate Solution
String regex = "^0+";
return digits.replaceAll(regex, "");
}
removeLeadingZeros("0123"); //Result -> 123
removeLeadingZeros("00000456"); //Result -> 456
removeLeadingZeros("000102030"); //Result -> 102030
Convert input to StringBuilder
Use deleteCharAt method to remove character from beginning till non-zero character is found
String trimZero(String str) {
StringBuilder strB = new StringBuilder(str);
int index = 0;
while (strB.length() > 0 && strB.charAt(index) == '0') {
strB.deleteCharAt(index);
}
return strB.toString();
}
You can use pattern matcher to check for strings with only zeros.
public static String removeLeadingZeroes(String value) {
if (Pattern.matches("[0]+", value)) {
return "0";
} else {
while (value.indexOf("0") == 0) {
value = value.substring(1);
}
return value;
}
}
You can try this:
1. If the numeric value of the string is 0 then return new String("0").
2. Else remove the zeros from the string and return the substring.
public static String removeLeadingZeroes(String str)
{
if(Double.parseDouble(str)==0)
return new String("0");
else
{
int i=0;
for(i=0; i<str.length(); i++)
{
if(str.charAt(i)!='0')
break;
}
return str.substring(i, str.length());
}
}
Use String.replaceAll(), like this:
public String replaceLeadingZeros(String s) {
s = s.replaceAll("^[0]+", "");
if (s.equals("")) {
return "0";
}
return s;
}
This will match all leading zeros (using regex ^[0]+) and replace them all with blanks. In the end if you're only left with a blank string, return "0" instead.
int n = 000012345;
n = Integer.valueOf(n + "", 10);
It is important to specify radix 10, else the integer is read as an octal literal and an incorrect value is returned.
public String removeLeadingZeros(String num) {
String res = num.replaceAll("^0+", "").trim();
return res.equals("")? "0" : res;
}
I have found the following to be the simplest and most reliable, as it works for both integers and floating-point numbers:
public static String removeNonRequiredLeadingZeros(final String str) {
return new BigDecimal(str).toPlainString();
}
You probably want to check the incoming string for null and blank, and also trim it to remove leading and trailing whitespace.
You can also get rid of trailing zeros by using:
public static String removeNonRequiredZeros(final String str) {
return new BigDecimal(str).stripTrailingZeros().toPlainString();
}
My goal is to change any form of the word "java" in a sentence to "JAVA".I've got everything done but my code won't read in mixed cases for example:JaVa, JAva,etc. I know I am suppose to use toUpperCase and toLowerCase or equalsIgnoreCase but I am not sure how to use it properly. I am not allowed to use replace or replace all, teacher wants substring method.
Scanner input=new Scanner(System.in);
System.out.println("Enter a sentence with words including java");
String sentence=input.nextLine();
String find="java";
String replace="JAVA";
String result="";
int n;
do{
n=sentence.indexOf(find);
if(n!=-1){
result =sentence.substring(0,n);
result=result +replace;
result = result + sentence.substring(n+find.length());
sentence=result;
}
}while(n!=-1);
System.out.println(sentence);
}
}
You can't do that using String.indexOf because it is case sensitive.
The simple solution is to use a regex with a case insensitive pattern; e.g.
Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(str).replaceAll(repl);
That also has the benefit of avoiding the messy string-bashing you are currently using to do the replacement.
In your example, your input string is also valid as a regex ... because it doesn't include any regex meta-characters. If it did, then the simple workaround is to use Pattern.quote(str) which will treat the meta-characters as literal matches.
It is also worth nothing that String.replaceAll(...) is a "convenience method" for doing a regex replace on a string, though you can't use it for your example because it does case sensitive matching.
For the record, here is a partial solution that does the job by string-bashing. #ben - this is presented for you to read and understand ... not to copy. It is deliberately uncommented to encourage you to read it carefully.
// WARNING ... UNTESTED CODE
String input = ...
String target = ...
String replacement = ...
String inputLc = input.lowerCase();
String targetLc = target.lowerCase();
int pos = 0;
int pos2;
while ((pos2 = inputLc.indexOf(targetLc, pos)) != -1) {
if (pos2 - pos > 0) {
result += input.substring(pos, pos2);
}
result += replacement;
pos = pos2 + target.length();
}
if (pos < input.length()) {
result += input.substring(pos);
}
It probably be more efficient to use a StringBuilder instead of a String for result.
you are allowed to use toUpperCase() ? try this one
Scanner input=new Scanner(System.in);
System.out.println("Enter a sentence with words including java");
String sentence=input.nextLine();
String find="java";
String replace="JAVA";
String result="";
result = sentence.toLowerCase();
result = result.replace(find,replace);
System.out.println(result);
}
reply with the result :))
Update : Based on
I've got everything done but my code won't read in mixed cases for
example:JaVa, JAva,etc.
you can use your code
Scanner input=new Scanner(System.in);
System.out.println("Enter a sentence with words including java");
String sentence=input.nextLine();
String find="java";
String replace="JAVA";
String result="";
int n;
do{
//for you to ignore(converts the sentence to lowercase) either lower or upper case in your sentence then do the nxt process
sentence = sentence.toLowerCase();
n=sentence.indexOf(find);
if(n!=-1){
result =sentence.substring(0,n);
result=result +replace;
result = result + sentence.substring(n+find.length());
sentence=result;
}
}while(n!=-1);
System.out.println(sentence);
}
Update 2 : I put toLowerCase Convertion outside the loop.
public static void main(String[] args){
String sentence = "Hello my name is JAva im a jaVa Man with a jAvA java Ice cream";
String find="java";
String replace="JAVA";
String result="";
int n;
//for you to ignore(converts the sentence to lowercase) either lower or upper case in your sentence then do the nxt process
sentence = sentence.toLowerCase();
System.out.println(sentence);
do{
n=sentence.indexOf(find);
if(n!=-1){
result =sentence.substring(0,n);
result=result +replace;
result = result + sentence.substring(n+find.length());
sentence=result;
}
}while(n!=-1);
System.out.println(sentence);
}
RESULT
hello my name is java im a java man with a java java ice cream
hello my name is JAVA im a JAVA man with a JAVA JAVA ice cream
A quick solution would be to remove your do/while loop entirely and just use a case-insensitive regex with String.replaceAll(), like:
sentence = sentence.replaceAll("(?i)java", "JAVA");
System.out.println(sentence);
Or, more general and according to your variable namings:
sentence = sentence.replaceAll("(?i)" + find, replace);
System.out.println(sentence);
Sample Program
EDIT:
Based on your comments, if you need to use the substring method, here is one way.
First, since String.indexOf does case-sensitive comparisons, you can write your own case-insensitive method, let's call it indexOfIgnoreCase(). This method would look something like:
// Find the index of the first occurrence of the String find within the String str, starting from start index
// Return -1 if no match is found
int indexOfIgnoreCase(String str, String find, int start) {
for(int i = start; i < str.length(); i++) {
if(str.substring(i, i + find.length()).equalsIgnoreCase(find)) {
return i;
}
}
return -1;
}
Then, you can use this method in the following manner.
You find the index of the word you need, then you add the portion of the String before this word (up to the found index) to the result, then you add the replaced version of the word you found, then you add the rest of the String after the found word.
Finally, you update the starting search index by the length of the found word.
String find = "java";
String replace = "JAVA";
int index = 0;
while(index + find.length() <= sentence.length()) {
index = indexOfIgnoreCase(sentence, find, index); // use the custom indexOf method here
if(index == -1) {
break;
}
sentence = sentence.substring(0, index) + // copy the string up to the found word
replace + // replace the found word
sentence.substring(index + find.length()); // copy the remaining part of the string
index += find.length();
}
System.out.println(sentence);
Sample Program
You could use a StringBuilder to make this more efficient since the + operator creates a new String on each concatenation. Read more here
Furthermore, you could combine the logic in the indexOfIgnoreCase and the rest of the code in a single method like:
String find = "java";
String replace = "JAVA";
StringBuilder sb = new StringBuilder();
int i = 0;
while(i + find.length() <= sentence.length()) {
// if found a match, add the replacement and update the index accordingly
if(sentence.substring(i, i + find.length()).equalsIgnoreCase(find)) {
sb.append(replace);
i += find.length();
}
// otherwise add the current character and update the index accordingly
else {
sb.append(sentence.charAt(i));
i++;
}
}
sb.append(sentence.substring(i)); // append the rest of the string
sentence = sb.toString();
System.out.println(sentence);
I have a String "speed,7,red,fast". I want to replace the 7 by a String "Seven". How do I do that ?
More details -
7 can be replaced by ANY string and not just "Seven". It could also be "SevenIsHeaven".
I don't want to replace all occurrences of 7. Only 7 at the specified index, ie use the index of 7 to replace 7 by some string.
replaceAll("7", "Seven") //simple as that
EDIT
Then you should look for the specified index.
String input = "test 7 speed,7,red,fast yup 7 tr";
int indexInteresdIn = 13;
if(input.charAt(indexInteresdIn) == '7'){
StringBuilder builder = new StringBuilder(input);
builder.replace(indexInteresdIn, indexInteresdIn+1, "Seven");
System.out.println(builder.toString());
}
Because String is immutable you should use StringBuilder for better performance.
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
yourStringBuiler.replace(
yourStringBuiler.indexOf(oldString),
yourStringBuiler.indexOf(oldString) + oldString.length(),
newString);`
If you want to replace a whole String like the String.replaceAll() does you could create an own function like this:
public static void replaceAll(StringBuilder builder, String from, String to)
{
int index = builder.indexOf(from);
while (index != -1)
{
builder.replace(index, index + from.length(), to);
index += to.length(); // Move to the end of the replacement
index = builder.indexOf(from, index);
}
}
Source:
Replace all occurrences of a String using StringBuilder?
However if you doesn't need it frequently and performance is not that important a simple String.replaceAll() will do the trick, too.
How about simply like below ?
String str = "speed,7,red,fast";
str = str.replace("7", "Seven");
7 can be replaced by ANY string and not just "Seven". It could also be
"SevenIsHeaven". I don't want to replace all occurrences of 7. Only 7
at the specified index.
Or if you wanna use regex to replace the first numeric to a meaningful String.
String str = "speed,7,red,fast";
str = str.replaceFirst("\\d", "Seven");
better way is to store the string itself in an array, spiting it at a space.
String s[];
static int index;
s = in.readLine().spilt(" ");
Now scan the array for the specified word, at the specified index and replace that with the String you desire.
for(int i =0;i<s.length; i++)
{
if((s[i] == "7")&&(i==index))
{
s[i]= "Seven";
}
}
is there a nice way for creating a string initialized with a number of characters given an int (counter) and the character to set.
Simply put I would like a method that returns "#,#,#,#,#" when passed 5 and # as parameter.
Any ideas?
Using the StringUtils utility in the Apache Commons lang library:
String myString = StringUtils.repeat("#", ",", 5);
If you only want the characters (and not the comma separators), it is just:
String myString = StringUtils.repeat("#", 5);
It's pretty simple to write a method for this:
public static String createPlaceholderString(char placeholder, int count) {
StringBuilder builder = new StringBuilder(count * 2 - 1);
for (int i = 0; i < count; i++) {
if (i!= 0) {
builder.append(',');
}
builder.append(placeholder);
}
return builder.toString();
}
(Note that we can initialize the builder with exactly the right size of buffer as we know how big it will be.)
You could use something like Strings.repeat from Guava:
String text = Strings.repeat("#,", count - 1) + "#";
Or even more esoterically:
String text = Joiner.on(',').join(Iterables.limit(Iterables.cycle("#"), count));
... but personally I'd probably stick with the method.
Try:
public String buildString(int nbr, String repeat){
StringBuilder builder = new StringBuilder();
for(int i=0; i>nbr; i++){
builder.append(repeat);
if(i<(nbr-1))
builder.append(",");
}
return builder.toString();
}
If I have a string such as one of the following:
AlphaSuffix
BravoSuffix
CharlieSuffix
DeltaSuffix
What is the most concise Java syntax to transform AlphaSuffix into Alpha into BravoSuffix into Bravo?
Use a simple regexp to delete the suffix:
String myString = "AlphaSuffix";
String newString = myString.replaceFirst("Suffix$", "");
Chop it off.
String given = "AlphaSuffix"
String result = given.substring(0, given.length()-"Suffix".length());
To make it even more concise, create a utility method.
public static String chop(String value, String suffix){
if(value.endsWith(suffix)){
return value.substring(0, value.length() - suffix.length());
}
return value;
}
In the utility method, I've added a check to see if the suffix is actually at the end of the value.
Test:
String[] sufs = new String[] {
"AlphaSuffix",
"BravoSuffix",
"CharlieSuffix",
"DeltaSuffix"
};
for (int i = 0; i < sufs.length; i++) {
String s = chop(sufs[i], "Suffix");
System.out.println(s);
}
Gives:
Alpha
Bravo
Charlie
Delta
if suffixes are all different/unkown you can use
myString.replaceFirst("^(Alpha|Bravo|Charlie|Delta|...).*", "$1");