Separate items from strings

Source: Internet
Author: User

Q: There is a string STR = "// 192.169.3.3: 3306: User: Pwd"
How to use C ++ to isolate IP addresses, port numbers, user names, and passwords. Note that the port number may not exist (with default values. Thank you.

A.

(1)

# Include<Iostream># Include<String>

Using NamespaceSTD;

Int Main ()
{
Const String Str = " // 192.169.3.3: 3306: User: pwd " ;
String TMP;
Size_t POS = 2 ;
TMP = Str. substr (Pos, str. Find ( ' : ' ));
Cout < TMP;
...

Return 0;
}

(2)

# Include<Iostream># Include<Deque>
# Include<Vector>
Using NamespaceSTD;

Void Parse ( Const Char * Str)
{
Char IP [ 32 ], User [ 32 ], PWD [ 32 ];
Int Port = 0 ;
If (Sscanf (STR, " // % [^:]: % D: % [^:]: % s " , IP, & Port, user, PWD) ! = 4 )
Sscanf (STR, " // % [^:]: % [^:]: % S " , IP, user, PWD );
Printf ( " // % S: % d: % s \ n " , IP, port, user, PWD );
}

IntMain (Void)
{
Parse ("// 192.169.3.3: 3306: User: pwd");
Parse ("// 192.169.3.3: User: pwd");
Return 0;
}

 

(3)

Void parse (string Str)
{
String IP (""), user (""), PWD ("");
Int port (80 );
Int c = count (Str. Begin (), str. End (),':');
STR = Str. substr (2 );
Replace (Str. Begin (), str. End (),':','');

Stringstream is (STR );

If (C = 2)
Is> ip> User> pwd;
Else
If (C = 3)
Is> ip> port> User> pwd;

Cout <IP <Endl;
Cout <port <Endl;
Cout <user <Endl;
Cout <PWD <Endl;

}

You can also use stringstream.

 

 

(4)

# Include<String. H># Include<Stdio. h>

Int Main ()
{
Char STR [] = " // 192.169.3.3: 3306: User: pwd " ;
Char * P;
P = Strtok (STR, " : " );
While (P)
{
Printf ( " % S \ n " , P );
P = Strtok (null, " : " );
}
Return 0 ;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.