开发者

Android string processing from TCP stream

I have a very basic TCP socket connection to a remote device that I can poll for status.

Aside from the socket programming, which I have mostly figured out through asynctask, I'm trying to come up with a way to parse out the returning string.

  1. I query the device with something like "VOL?"
  2. The device responds with the Volume of 12 different audio outputs with this: "VOL:33,0,21,12,0,43,0,0,0,0,20,0"

The ":" character always and only comes back after the echo of the initial command, so I can use whatever comes before the colon to flag what sort of answer is coming in. (VOL, BAS, MUT, TRE, BAL, etc) In the case of VOL, I simply want to chunk out everything that comes between the commas, so I can chop up and place into an array the volumes of all zones.

The only thing I can think of is to grab the length of the string, then run a for loop through it searching for commas one by one, but it seems ridiculously messy:

    int oldPos = 0; //used in the upcoming 'if clause' to mark where the last comma was found
    int y = 0;      //used to old the resulting value's array position
    String strIncoming; = //the incoming TCP string
        for(int x = 0; x <= strIncoming.length(); x++){
            if(",".equals(strIncoming[x]){
                volzoneVal[y] = strIncoming.subString(oldPos,x);
                oldPos = x;
                y++;
            }
      开发者_JAVA百科   }

there has GOT to be a better way, (and I'm not even sure this is going to work, I'm typing it here for the first time as I brainstorm this problem, so it's not been run or compiled)

Is there a better way to scan through a string looking for hits?


strIncoming.split(":")[0] will give you what was before first colon

strIncoming.split(":")[1].split(",") will give you array of individual strings


First, split the string on the colon, and then split[0] is your type. Then take split[1] and split it on the comma, and you'll have all your 12 different outputs ready to go (just convert them to integers).


Use Java's string split function and split on the comma as the delimiter. You will then have an array of your parameters. If you append some kind of "end string" character to each response, you will know the start and end based on the colon for the start and your end character for the end.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜