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 ;
}