Is there anyway to delete a specified character in a string? - java

This is my code
public class StringTest {
public static void main(String []args) {
String str= "8650";
StringBuilder build = new StringBuilder(str);
char index = str.charAt(0);
System.out.println(index+"");
int indexStr= build.indexOf(index+"");
System.out.println(indexStr);
for( int i = 0; i < str.length(); i++) {
if(indexStr == 0)
build.deleteCharAt(indexStr);
}
System.out.println(build);
}
}
I want to delete thé first number if it’s 0
So if I have 8650 it will print 8650, instead if I have 0650 it will print 650.

You have made things complicated,just use String.startsWith() and String.substring()`` can do it
public class StringTest {
public static void main(String[] args) {
String str = "8650";
str = "0650";
if (str.startsWith("0")) {
str = str.substring(1);
}
System.out.println(str);
}
}

Below code might help you.
public static void main(String[] args) {
String val = "10456";
val = (val.charAt(0) == '0') ? val.substring(1, val.length()) : val;
System.out.println(val);
}

It will remove all leading zero.
public static void main(String[] args) {
String str = "000650";
str = str.replaceFirst("^0*", "");
System.out.println(str); // output 650 it will remove all leading zero
}

Related

Is there any simple way to convert camel-case to snake-case correctly?

I tried as the below code code snippet, but the TradeID is printing as Trade_I_D, but it must be as Trade_ID.
input: getCurrency, getAccountName, getTradeID
expected output: Currency, Account_Name, Trade_ID
public class RemoveGet {
public static void main(String args[]) {
for (String a : args) {
String b = a.replace("get", "");
//System.out.println(b);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length(); i++) {
if (Character.isUpperCase(b.charAt(i))) {
sb.append("_");
sb.append(b.charAt(i));
} else {
sb.append(b.charAt(i));
}
}
//System.out.println(sb.toString());
String c = sb.toString();
if (c.startsWith("_")) {
System.out.println(c.substring(1));
}
}
}
}
try this
str = str.replace("get", "")
.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2")
.replaceAll("([a-z])([A-Z])", "$1_$2")
Use a boolean first-time switch to only put an underscore after the second upper case letter.
Here are some test results.
getTradeID
Trade_ID
Here's the complete runnable code.
public class RemoveGet {
public static void main(String args[]) {
args = new String[1];
args[0] = "getTradeID";
for (String a : args) {
System.out.println(a);
String b = a.replace("get", "");
boolean firstTimeSwitch = true;
// System.out.println(b);
StringBuffer sb = new StringBuffer();
sb.append(b.charAt(0));
for (int i = 1; i < b.length(); i++) {
if (firstTimeSwitch && Character.isUpperCase(b.charAt(i))) {
sb.append("_");
sb.append(b.charAt(i));
firstTimeSwitch = false;
} else {
sb.append(b.charAt(i));
}
}
System.out.println(sb.toString());
}
}
}
Instead of writing all logic in the main function, write some functions to do small tasks and call them in the main function. This makes the code readable and easy to debug. This could be the possible solution code:
public class RemoveGet {
public static String addUnderScoreAppropriately(String input) {
String result = "";
String underScore = "_";
for(int i=0; i<input.length();i++) {
if((Character.isUpperCase(input.charAt(i))) && (i != 0)) {
result = result + underScore + input.charAt(i);
}else{
result = result + input.charAt(i);
}
}
result = result.replace("_I_D","_ID");
return result;
}
public static void main(String args[]) {
for (String a : args) {
System.out.println(addUnderScoreAppropriately(a.replace("get","")));
}
}
}

How do I separate words using split() string method in Java

I want to separate words and print them in a single line with a hyphen(-) in between. I have written the following code but it only prints the last word followed by a hyphen i.e. the output is carrot-. I don't understand why and what changes do I make to get the desired output?
public class SeparatingWords {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String[] words = str.split(" ");
String result = null;
for (int i = 0; i < words.length; i++) {
result=words[i]+"-";
}
return result;
}
}
Instead of calling a split and concatenating the string, why can't you directly call replaceAll directly to achieve your goal. This will make your code simple.
String result = str.replaceAll(" ", "-");
Below is sample modified code of yours. Hope this helps
public class Sample {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String result = str.replaceAll(" ", "-");
return result;
}
}
If you want to perform any other operation based on your requirement inside the method, then below should work for you. As suggested by #Moler added += and initialized the result object
public static String separatingWords(String str) {
String[] words = str.split(" ");
String result = ""; // Defaulted the result
for (int i = 0; i < words.length-1; i++) {
result += words[i] + "-"; // Added a +=
}
result += words[words.length - 1];
return result;
}
public class SeparatingWords
{
public static void main(String[] args)
{
String str="apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str)
{
String[] words=str.split(" ");
String result="";
for(int i=0;i<words.length;i++)
{
result += words[i]+"-";
}
return result;
}
}
Try this code:
public class SeparatingWords
{
public static void main(String[] args)
{
String str="apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str)
{
String[] words=str.split(" ");
String result=words[0];
for(int i=1;i<words.length;i++)
{
result=result+"-"+words[i];
}
return result;
}
}
You could use s StringBuilder, append the single word and a hyphon and at the last word, you just append the word:
public class SeparatingWords {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String[] words = str.split(" ");
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
resultBuilder.append(words[i]);
if (i != words.length - 1) {
resultBuilder.append("-");
}
}
return resultBuilder.toString();
}
}
String[] words = str.split(" ");
// perform operations on individual words
return String.join("-", words);

How do I split a string by a multiple-string delimiter in Java?

public class SplitTest {
public static void main(String[] args) {
String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String[] strToSplit = new String[] { "GH", "MN" };
for (String de : strToSplit) {
if (string.contains(de)) {
String[]str = string.split(de);
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
}
}
Output :
ABCDEF,IJKLMNOPQRSTUVWXYZ,ABCDEFGHIJKL,OPQRSTUVWXYZ
but actual output is :
ABCDEF,IJKL,OPQRSTUVWXYZ
You can do it another way like replace string by unique delimiter at first place instead of splitting string at first place .Later you can split whole string by unique delimiter. for ex.
public class SplitTest {
public static void main(String[] args) {
String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String str;
String[] strToSplit = new String[] { "GH", "MN" };
for (String de : strToSplit) {
if (string.contains(de)) {
str = string.replace(de,unique_delimiter);
}
}
String [] finalString = str.split(unique_delimiter);
for (int i = 0; i < finalString.length; i++) {
System.out.println(finalString[i]);
}
}
}
Hope this would help.

How can return part of a string between two comma characters?

say I'm given a set of strings that looks like this:
0,test0,dummy
1,test,dummy
2,test1,dummy
3,test2,dummy
4,test3,dum,dum,dummy
I wrote code that can return only what's before the last ",":
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
while (testIn.hasNextLine()) {
String line = testIn.readLine();
String result = line.substring(0, line.lastIndexOf(","));
List<String> synList = Arrays.asList(result.split(","));
for (String i : synList) {
System.out.println(i);
}
}
}
}
What I intended to do was only return the part of the string that was between the first and second "," characters, so my code above doesn't work for the last line of text. How do I only return what's between the first and second comma?
In this case, only test0, test, test1, test2, and test3.
thanks!
use split() method like this :
public static void main(String[] args) {
String s = "0,prop,dummy";
System.out.println(s.split(",")[1]);
}
O/P:
prop
NOTE : You have to check whether the String contains atleast 1 , (unless you want an ArrayIndexOutOfBoundsException :P)
Rather than using lastIndexOf, use indexOf twice:
int pos = line.indexOf(',', line.indexOf(',')+1);
String result = line.substring(0, pos);
You could use string.replaceAll function.
string.replaceAll("(?m)^[^,]*,|,.*", "");
DEMO
String s = "0,test0,dummy\n" +
"1,test,dummy\n" +
"2,test1,dummy\n" +
"3,test2,dummy\n" +
"4,test3,dum,dum,dummy";
System.out.println(s.replaceAll("(?m)^[^,]*,|,.*", ""));
What about StringTokenizer?
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
StringTokenizer stok = null;
while (testIn.hasNextLine()) {
String line = testIn.readLine();
stok = new StringTokenizer(line,",");
for(int i = 0; i< stok.countTokens() ; i++){
String str = st.nextToken();
if( i == 1){
System.out.println(str);
}else if( i > 1){break;}
}// for
}// while
}//main
}//class

Java Split a String with coma or 0(zero) followed by a whitespace

If I have a string, e.g.
s = "david,marko,rita,0 megan,0 vivian,law";
I need split this string into
david
marko
rita
megan
vivian
law
I am trying with
String arr[] = s.split("[,\\s]");
but didn´t work. Any suggestions?
You could use this expression:
String arr[] = s.split(",0?\\s*");
Or maybe even:
String arr[] = s.split("[,0\\s]+");
Which one you want is unclear from the example.
Your regex is : "(,0 |,)"
So try this code :
public static void main(String[] args){
String s = "david,marko,rita,0 megan,0 vivian,law";
String[] ss = s.split("(,0 |,)");
for (int i = 0; i < ss.length; i++) {
String string = ss[i];
System.out.println(string);
}
}
Just an advice
Rather then splitting with multiple values try this
import java.util.*;
class test {
public static void main(String[] args) {
String s = "david,marko,rita,0 megan,0 vivian,law";
System.out.println(Arrays.toString(s.replace("0","").replace(" ","").split(",")));
}
}
You can try this:
public class SplitTest {
public static void main(String[] args) {
String inputString = "david,marko,rita,0 megan,0 vivian,law";
String splits[] = inputString.split(",0?\\s*");
for (String split : splits) {
System.out.println(split);
}
}
}
String[] arr = s.split(",(0\\s+)*");
The regex splits on a comma followed optionally by a 0 and one or more spaces.
public static void main(String[] args) {
String s = "da0vid,marko,rita,0 megan,0 vivian,law";
String[] arr = s.split(",(0\\s+)*");
for (int i = 0; i < arr.length; i++)
System.out.println("'"+arr[i]+"'");
}
=>
'da0vid'
'marko'
'rita'
'megan'
'vivian'
'law'

Categories