Mistu4u
Mistu4u

Reputation: 5416

Substring a string based on presence of a character

I have a string: LOAN,NEFT,TRAN. I want to substring the string based on getting a , during traversing the string. So I tried to first get a count for how many , are there. but not sure what function to user to get what I want. Also this should be dynamic, meaning I should be able to create as many substrings as required based on number of ,s. I tried the following code:

   package try1;

   public class StringTest {


    public static void main(String[] args) {
        String str="LOAN,NEFT,TRAN";
        int strlen=str.length();
        int count=0;
        for(int i=0;i<strlen;i++)
        {
            if(str.contains("'"))
            count++;
        }
        System.out.println(""+count);

        for (int j=0;j<count;j++)
        {
            //code to create multiple substrings out of str
        }
    }
   }

But I do not think contains() is the function I am looking for because value of count here is coming 0. What should I use?

Upvotes: 0

Views: 135

Answers (2)

nitishagar
nitishagar

Reputation: 9413

You can use split to get substrings directly:

String[] substrings = str.split(",");

Is this what you want as an output: (shown below)?

["LOAN", "NEFT", "TRAN"] // Array as an output

Or to just get the count of the splitting char, you can use the same line as above with this:

int count = substrings.length - 1;

Upvotes: 2

Adam
Adam

Reputation: 36703

Your code doesn't actually count the , characters because 1) contains doesn't take into account your loop variable 2) it's searching for ', not ,

Assuming you want to work at a low level rather than using high level functions like .split(), then I'd recommend the following.

for(char c : str.toCharArray()) {
    if (c == ',') {
       count++;
    }
}

Upvotes: 2

Related Questions