How to handle paths in C + + (string)

Source: Internet
Author: User

The string class provides strings handling functions that allow programmers to find characters within a string, extract sequential sequences of characters (called substrings ), and delete and add them in a string. We'll cover some of the main functions.

1. FunctionsFind_first_of () andFind_last_of () performs a simple pattern match, such as finding a single character in a stringC. FunctionFind_first_of () Find in string1 occurrences of a characterc, while the functionFind_last_of () to find the last occurrence of theC. The matching position is the return value. If no match occurs, the function returns-1.

int find_first_of (char c, int start = 0):
Find the string in the1 occurrences ofC, by locationStart. If there is a match, the matching position is returned;-1. By default,Start for0, the function searches the entire string.

int find_last_of (char c):
Finds the last occurrence in a stringC. If there is a match, the matching position is returned;-1. The search finds a match at the end of the character, so no starting position is provided.

Example:
String str = "Mississippi";
int index;
' s ' inIndex is2.3.5.Appears at 6
index = str.find_first_of (' s ', 0); Index is2
index = str.find_first_of (' s ', 4); Index is5
index = str.find_first_of (' s ', 7); Index is-1

The last appearance of ' s ' inindex= 6
index = str.find_last_of (' s ');
While loop outputs eachThe ' I 'Index
while (index = str.find_first_of (' i ', index))!! =-1)
{
cout << "index" << index << "";
index++; Restart search at Next indx
}

Output Result:Index 1 Index 4 Index 7 index 10

2. Extracting consecutive character sequences in a string, both substrings.
This operation assumes that the positionStart and number of charactersCount.

string substr (int start=0,int count=-1);
Copy the string from the start position.Count characters, and return these characters as substrings.
If the trailing string is less thanCount character orCount is-1, the end of the string stops copying.
If you do not use a parameter call to include only the locationStart, thenSUBSTR () returns a substring starting from the position to the tail of the string.

The Find () function finds the specified pattern in a string. The function converts the stringS and positionStart as a parameter, and findS is matched as a substring.

int find (const string& s,int start = 0):
The search obtains a stringS and positionStart, and look forS is matched as a substring. If there is a match, the matching position is returned;-1. By default,Start for0, the function searches the entire string.

Example:
String fullname = "Mark Tompkin", FirstName, LastName;
int index;

index = str.find_last_of ("); Index is 4
FirstName = "Mark" LastName = "Tompkin"
FirstName = fullname.sub string (0,index);
LastName = Fullname.substring (index+1);

index = fullname.find ("kin"); Inindex = 9 Match"Kin"
index = Fullname.find ("Omp", 0); Inindex = 6 Match"Omp"
index = Fullname.find ("Omp", 7); Index Is-1 (no match)

3. Adding and removing strings

Character connections++ =) is a string that is added at the end of the string.The insert () function expands this capability to allow strings to be added at any location. In order to get from the string. In order to remove the string from the string,
FunctionErase () can delete characters starting at the specified position.

void Insert (int statr,const string& s):
The substrings into the string, starting at positionStart The insert operation increases the length of the original string.

void Erase (int start=0,int count=-1):
FromStart, remove from stringCount of characters. If the existing string is less thanCount of characters, orCount is-1, delete all characters to the end of the string. By default, Start for0, the function deletes the string from the beginning of the string. By default, the function is also deleted to the end of the string. Note that you do not use parameters to callErase () function, the string is truncated to a length ofAn empty string of 0.

Example:
String str = "Endfile";
string s = "string Object type";
str + = "Mark";
Str.inset (3, "-of-"); STR is"End-of-file Mark"
S.erase (7,7); S is"String Type"
FromIndex isDelete at 34 characters
S.erase (3,4);
cout << S; Output:"Strtype"

4.C_STR () returnsThe address of the C-language style string.
Converts a string object to aC language style string.
Char *c_str ();
Returns an equivalent of a string object.The address of the C-language style string. return typechar* saysC Language Style stringA 1-character address.

Example:
string filename = "Input.dat";
Open requires that the file name isC-Language style strings
Fin.open (Filename.c_str ());

5. Methods for separating string paths

Programs that process files may want to parse the file name. This algorithm is used for string processing. The file can be specified by path name, and the path name includes the delimiterThe name set of the "\" split. Last oneThe name sequence before "\" is called a path. The last name is the file name and may also include the extension.

Path name\class\programs\testfile.cpp
Path\class\programs\
FilenameTestfile.cpp
Extended NameCpp

To parse the file name, we read the full pathname from the keyboard and output the path and file name. If the file name has an extension"CPP", when you create the executable file name, you will use the' exe ' override extension"CPP". The following is the outline of the program structure, and the description of how to use the String function:

1. Enter the file name, use the functionFind_last_of () searches the string for the last occurrence of the"\"。 This character determines the end of the path and the beginning of the file name.
2. The path is the last oneA substring consisting of all strings before "\". The file name is the last oneAll characters after "\". Use the lastThe location of "\" andSUBSTR () Extracts the path and file name.
3. The extension is one of the best names in the file name"." After the string. CallFind_last_of () searches for the last match, copies the file name, deletes the current extension, and adds a new extension"EXE". The executable file name produced by the output.

FilePrg1_3.cpp
This program prompts the user to enter a path to the file
It uses the string class operation to identify and output
Path name and file name. If the file name has
Extension "CPP", create and output
The name of the executable file with an extension of "EXE", replacing
Name extension "CPP"

WJ.cpp: Defines the entry point of the console application.
//
#I nclude "stdafx.h"
#I nclude<iostream>
#I nclude<string>

using namespace Std;

int main ()
{
String pathname, path, filename,executablefile;
' \ ' and '. ' The location
int Backslashindex, Dotindex;
cout << "Enter The path name:";
CIN >> Pathname;

Identify the location of the last ' \ '. Note: because
Escape codes such as ' \ n ' start with \
C + + uses ' \ \ ' to represent \

Backslashindex = pathname.find_last_of (' \ \ ');

The path name is the last character before the ' \ '
Path = Pathname.substr (0,backslashindex);

cout << "path:" << path << Endl;

//  path name trailer is the file name
FileName = pathname.substr (backslashindex+1,-1);
cout << "FileName:" << filename << endl;

See if the file name has a '. cpp ' extension.
First find the last one '. ' The location. If
No '. ', then Dotindex is -1
Dotindex = filename.find_last_of ('. ');
Test for '. ', whether the remaining characters are "CPP"
if (dotindex! =-1 && filename.substr (dotindex+1) = = "CPP")
{
Remove "CPP" and add "EXE" to set executable string
Executablefile = filename;
Executablefile.erase (dotindex+1,3);
executablefile+= "EXE";
cout << "executable:" << executablefile << Endl;
}

return 0;
}
Output Result:
The1 times allowed Results:

Enter The path name: \class\programs\testfile
Path: \class\programs
Filename:testfile

The2 times allowed Results:

Enter the path name:programs\strings\filedemp.cpp
Path:programs\strings
Filename:filedemo.cpp
Executable:filedemo.exe

3 results allowed:

Enter The path name: \program.cpp
Path
Filename:program.cpp
Executable:program.exe

How to handle paths in C + + (string)

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.