4

I using split method to split the String.

String date = "2020-10-07";
date.split("-");
print("split " + date[0]);

I expect will get 2020, but why it return 2 ?

4
  • Your date is still a String. Yo should assign the return value of ::split to an array var. Commented Oct 15, 2020 at 17:07
  • @AndrewCheong I actually reading this tutorialkart.com/dart/dart-split-string. The String will become list after using split, no? Commented Oct 15, 2020 at 17:09
  • 1
    Nope, in that reference you also see it returning a list of strings. Commented Oct 15, 2020 at 17:12
  • You are still using the same date object it is immutable use print( date.split('-')[0]); Commented Oct 15, 2020 at 17:14

3 Answers 3

3

The reason you are getting 2 is because it is the first position (0) of the string variable date.

When you split a string, it will return a list/array.

String date = "2020-10-07";
final dateList = date.split("-");
print("split " + dateList[0]);
//expected "split 2020"
Sign up to request clarification or add additional context in comments.

Comments

1

It is 2 because there no change has been done to the variable date( the same without the split), but with split you can access the list like this below

String date = "2020-10-07";
var first = date.split("-").first;//returns the first element of the list
print("split " + first);

Comments

1

(Any String).split(Pattern) returns List<String>. Since no operation was done to change the variable (it anyhow can't store List<String>).

You are left with:

  1. Temporarily store the split as @Morgan Hunt and @Henok Suggested
  2. print("split " + date.split("-").first); (I guess you are going to return the first split)

Also data[0] -> is an operation on a string hence you are getting 0th position -> 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.