yes hello
yes hello

Reputation: 13

How do you split string at current position?

I am trying to split a line of text after every instance of '|', however I cant seem to figure it out. Here is what i have got so far

char special = '|';
for (int i = 0; i < blobs.length(); i++)
{
  if(blobs.charAt(i) == special)
  {
    String[] splitwords = blobs.split(charAt(i));
  }

Upvotes: 1

Views: 137

Answers (3)

user3115056
user3115056

Reputation: 1280

Why don't you simply use blobs.split("\|")

String[] split = blobs.split("\\|");

Upvotes: 1

Diego
Diego

Reputation: 216

You are over thinking this problem. You can simply do:

String[] splitBlobs = blobs.split('|')

This will return a list of strings with each element being before and after '|' but not the actual character.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140417

First, your code will split things, but puts it into a local variable, which isn't visible outside of that one if block. That simply doesn't make any sense.

But well, you dont need any of that. split() doesn't split at positions.

That method takes your split character, and splits the whole string accordingly.

Simply try

"some|string|with|pipes".split('|')

for example. If your question is: how could I split "sub strings", well: then you will have to first dissect your input string into multiple substrings, and then call split() on those different strings accordingly.

Beyond that: don't try to assume what such library methods do.

Get a good book or tutorial and research them, see this for example.

Upvotes: 2

Related Questions