当前位置: 首页>>代码示例>>C++>>正文


C++ BString::Length方法代码示例

本文整理汇总了C++中BString::Length方法的典型用法代码示例。如果您正苦于以下问题:C++ BString::Length方法的具体用法?C++ BString::Length怎么用?C++ BString::Length使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BString的用法示例。


在下文中一共展示了BString::Length方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: Visit

	virtual bool Visit(BPartition* partition, int32 level)
	{
		if (!partition->Parent()
			|| !fViewMap.ContainsKey(partition->Parent()->ID()))
			return false;

		// calculate size factor within parent frame
		off_t offset = partition->Offset();
//		off_t parentOffset = partition->Parent()->Offset();
		off_t size = partition->Size();
		off_t parentSize = partition->Parent()->Size();
		double scale = (double)size / parentSize;

		BString name = partition->ContentName();
		if (name.Length() == 0) {
			if (partition->CountChildren() > 0)
				name << partition->Type();
			else {
				char buffer[64];
				snprintf(buffer, 64, B_TRANSLATE("Partition %ld"),
					partition->ID());
				name << buffer;
			}
		}
		partition_id id = partition->ID();
		PartitionView* view = new PartitionView(name.String(), scale, offset,
			level, id);
		view->SetSelected(id == fSelectedPartition);
		PartitionView* parent = fViewMap.Get(partition->Parent()->ID());
		BGroupLayout* layout = parent->GroupLayout();
		layout->AddView(_FindInsertIndex(view, layout), view, scale);

		fViewMap.Put(partition->ID(), view);
		_AddSpaces(partition, view);

		return false;
	}
开发者ID:AmirAbrams,项目名称:haiku,代码行数:37,代码来源:DiskView.cpp

示例2: Fetch

/*!	\brief Tells the BQuery to start fetching entries satisfying the predicate.
	After Fetch() has been called GetNextEntry(), GetNextRef() and
	GetNextDirents() can be used to retrieve the enties. Live query updates
	may be sent immediately after this method has been called.
	Fetch() fails, if it has already been called. To reuse a BQuery object it
	has to be reset via Clear().
	\return
	- \c B_OK: Everything went fine.
	- \c B_NO_INIT: The predicate or the volume aren't set.
	- \c B_BAD_VALUE: The predicate is invalid.
	- \c B_NOT_ALLOWED: Fetch() has already been called.
*/
status_t
BQuery::Fetch()
{
    if (_HasFetched())
        return B_NOT_ALLOWED;

    _EvaluateStack();

    if (!fPredicate || fDevice < 0)
        return B_NO_INIT;

    BString parsedPredicate;
    _ParseDates(parsedPredicate);

    fQueryFd = _kern_open_query(fDevice, parsedPredicate.String(),
                                parsedPredicate.Length(), fLive ? B_LIVE_QUERY : 0, fPort, fToken);
    if (fQueryFd < 0)
        return fQueryFd;

    // set close on exec flag
    fcntl(fQueryFd, F_SETFD, FD_CLOEXEC);

    return B_OK;
}
开发者ID:mmadia,项目名称:haiku-1,代码行数:36,代码来源:Query.cpp

示例3:

/*static*/ BString
BUrl::_DoUrlEncodeChunk(const BString& chunk, bool strict, bool directory)
{
	BString result;

	for (int32 i = 0; i < chunk.Length(); i++) {
		if (_IsUnreserved(chunk[i])
				|| (directory && (chunk[i] == '/' || chunk[i] == '\\'))) {
			result << chunk[i];
		} else {
			if (chunk[i] == ' ' && !strict) {
				result << '+';
					// In non-strict mode, spaces are encoded by a plus sign
			} else {
				char hexString[5];
				snprintf(hexString, 5, "%X", chunk[i]);

				result << '%' << hexString;
			}
		}
	}

	return result;
}
开发者ID:,项目名称:,代码行数:24,代码来源:

示例4: GetEntry

bool DataFile::GetEntry(BString key, BString &result)
////////////////////////////////////////////////////////////////////////
{
	if (key.Length() == 0)
		return false;
	
	unsigned char hashcode = GetHash(key);
	DataEntry *tempentry;

	for (int i=0; i<m_Entries.CountItems(); i++)
	{
		tempentry = (DataEntry *)m_Entries.ItemAt(i);
		if (tempentry)
		{
			if (tempentry->HashValue == hashcode && tempentry->Key == key)
			{
				result = tempentry->Value;
				return true;
			}
		}
	}	
	
	return false;
}
开发者ID:PZsolt27,项目名称:GenesisCommander,代码行数:24,代码来源:Settings.cpp

示例5: entry

void
GrepWindow::_SetWindowTitle()
{
	BEntry entry(&fModel->fDirectory, true);
	BString title;
	if (entry.InitCheck() == B_OK) {
		BPath path;
		if (entry.GetPath(&path) == B_OK) {
			if (fOldPattern.Length()) {
				title = B_TRANSLATE("%appname% : %path% : %searchtext%");
				title.ReplaceAll("%searchtext%", fOldPattern.String());
			} else
				title = B_TRANSLATE("%appname% : %path%");

			title.ReplaceAll("%appname%", B_TRANSLATE(APP_NAME));
			title.ReplaceAll("%path%", path.Path());
		}
	}

	if (!title.Length())
		title = B_TRANSLATE(APP_NAME);

	SetTitle(title.String());
}
开发者ID:AmirAbrams,项目名称:haiku,代码行数:24,代码来源:GrepWindow.cpp

示例6: LoadAliases

void VisionApp::LoadAliases(void)
{
	BPath settingsPath;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &settingsPath) < B_OK) return;
	settingsPath.Append(kAliasPathName);
	if (settingsPath.InitCheck() < B_OK) return;
	BFile file(settingsPath.Path(), B_READ_ONLY);
	if (file.InitCheck() == B_OK) {
		BString data;
		char buffer[2048];
		memset(buffer, 0, sizeof(buffer));
		while (file.Read((void*)buffer, 2048) > 0) {
			data += buffer;
			memset(buffer, 0, sizeof(buffer));
		}
		file.Unset();
		while (data.Length() > 0) {
			BString cmd, value;
			int32 idx = data.IFindFirst("\t");
			if (idx != B_ERROR) {
				data.MoveInto(cmd, 0, idx);
				data.Remove(0, 1);
			} else {
				break;
			}
			idx = data.IFindFirst("\n");
			if (idx != B_ERROR) {
				data.MoveInto(value, 0, idx);
				data.Remove(0, 1);
			} else {
				break;
			}
			fAliases[cmd.ToUpper()] = value;
		}
	}
}
开发者ID:HaikuArchives,项目名称:Vision,代码行数:36,代码来源:Vision.cpp

示例7: entry

status_t
FilePlaylistItem::SetAttribute(const Attribute& attribute,
	const BString& string)
{
	switch (attribute) {
		case ATTR_STRING_NAME:
		{
			BEntry entry(&fRefs[0], false);
			return entry.Rename(string.String(), false);
		}
	
		case ATTR_STRING_KEYWORDS:
			return _SetAttribute("Meta:Keywords", B_STRING_TYPE,
				string.String(), string.Length());

		case ATTR_STRING_ARTIST:
			return _SetAttribute("Audio:Artist", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_AUTHOR:
			return _SetAttribute("Media:Author", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_ALBUM:
			return _SetAttribute("Audio:Album", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_TITLE:
			return _SetAttribute("Media:Title", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_AUDIO_BITRATE:
			return _SetAttribute("Audio:Bitrate", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_VIDEO_BITRATE:
			return _SetAttribute("Video:Bitrate", B_STRING_TYPE,
				string.String(), string.Length());

		default:
			return B_NOT_SUPPORTED;
	}
}
开发者ID:AmirAbrams,项目名称:haiku,代码行数:38,代码来源:FilePlaylistItem.cpp

示例8:

BString
HaikuMailFormatFilter::_ExtractName(const BString& from)
{
	// extract name from something like "name" <[email protected]>
	// if name is empty return the mail address without "<>"

	BString name;
	int32 emailStart = from.FindFirst("<");
	if (emailStart < 0) {
		name = from;
		return name.Trim();
	}

	from.CopyInto(name, 0, emailStart);
	name.Trim();
	if (name.Length() >= 2) {
		if (name[name.Length() - 1] == '\"')
			name.Truncate(name.Length() - 1, true);
		if (name[0] == '\"')
			name.Remove(0, 1);
		name.Trim();
	}
	if (name != "")
		return name;

	// empty name extract email address
	name = from;
	name.Remove(0, emailStart + 1);
	name.Trim();
	if (name.Length() < 1)
		return from;
	if (name[name.Length() - 1] == '>')
		name.Truncate(name.Length() - 1, true);
	name.Trim();
	return name;
}
开发者ID:AmirAbrams,项目名称:haiku,代码行数:36,代码来源:HaikuMailFormatFilter.cpp

示例9: start

void
PDFWriter::DrawString(char *string, float escapementNoSpace,
	float escapementSpace)
{
	REPORT(kDebug, fPage, "DrawString string=\"%s\", escapementNoSpace=%f, "
		"escapementSpace=%f, at %f, %f", string, escapementNoSpace,
		escapementSpace, fState->penX, fState->penY);

	if (IsDrawing()) {
		// text color is always the high color and not the pattern!
		SetColor(fState->foregroundColor);
	}
	// convert string to UTF8
	BString utf8;
	if (fState->beFont.Encoding() == B_UNICODE_UTF8) {
		utf8 = string;
	} else {
		ToUtf8(fState->beFont.Encoding()-1, string, utf8);
	}

	// convert string in UTF8 to unicode UCS2
	BString unicode;
	ToUnicode(utf8.String(), unicode);
	// need font object to calculate width of utf8 code point
	BFont font = fState->beFont;
	font.SetEncoding(B_UNICODE_UTF8);
	// constants to calculate position of next character
	const double rotation = DEGREE2RAD(fState->beFont.Rotation());
	const bool rotate = rotation != 0.0;
	const double cos1 = rotate ? cos(rotation) : 1;
	const double sin1 = rotate ? -sin(rotation) : 0;

	BPoint start(fState->penX, fState->penY);

	BeginTransparency();
	// If !MakesPDF() all the effort below just for the bounding box!
	// draw each character
	const char *c = utf8.String();
	const unsigned char *u = (unsigned char*)unicode.String();
	for (int i = 0; i < unicode.Length(); i += 2) {
		int s = CodePointSize((char*)c);

		float w = font.StringWidth(c, s);

		if (MakesPDF() && IsClipping()) {
			ClipChar(&font, (char*)u, c, s, w);
		} else {
			DrawChar(u[0]*256+u[1], c, s);
		}

		// position of next character
		if (*(unsigned char*)c <= 0x20) { // should test if c is a white-space!
			w += escapementSpace;
		} else {
			w += escapementNoSpace;
		}

		fState->penX += w * cos1;
		fState->penY += w * sin1;

		// next character
		c += s; u += 2;
	}
	EndTransparency();

	// text line processing (for non rotated text only!)
	BPoint end(fState->penX, fState->penY);
	BRect bounds;
	font_height height;

	font.GetHeight(&height);

	bounds.left = start.x;
	bounds.right = end.x;
	bounds.top = start.y - height.ascent;
	bounds.bottom = end.y   + height.descent;

	TextSegment* segment = new TextSegment(utf8.String(), start, escapementSpace,
		escapementNoSpace, &bounds, &font, pdfSystem());

	fTextLine.Add(segment);
}
开发者ID:AmirAbrams,项目名称:haiku,代码行数:82,代码来源:PDFText.cpp

示例10: main

int main(int argc, char* argv[])
{
	BApplication mailApp(APP_SIG);

	// No arguments, show usage
	if (argc < 2) {
		fprintf(stdout,"This program can only send mail, not read it.\n");
		fprintf(stdout,"usage: %s [-v] [-s subject] [-c cc-addr] "
			"[-b bcc-addr] to-addr ...\n", argv[0]);
		return 0;
	}

	char *subject = "No subject";
	char *cc = "";
	char *bcc = "";
	BString to;
	bool verbose = false;

	// Parse arguments
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-v") == 0)
			verbose = true;
		else if (strcmp(argv[i], "-s") == 0) {
			subject = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-c") == 0) {
			cc = argv[i+1];
			i++;
 		} else if (strcmp(argv[i], "-b") == 0) {
 			bcc = argv[i+1];
 			i++;
		} else {
			if (to.Length() > 0)
				to.Append(", ");
			to.Append(argv[i]);
		}
	}

	if (verbose) {
		fprintf(stdout, "\n");
		fprintf(stdout, "To:\t%s\n", to.String());
		fprintf(stdout, "Cc:\t%s\n", cc);
		fprintf(stdout, "Bcc:\t%s\n", bcc);
		fprintf(stdout, "Subj:\t%s\n", subject);
		fprintf(stdout, "\n");
	}

	// Check if recipients are valid
	if (strcmp(to.String(), "") == 0 &&
		strcmp(cc, "") == 0 &&
		strcmp(bcc, "") == 0) {

		fprintf(stderr, "[Error]: You must specify at least one recipient "
			"in to, cc or bcc fields.\n");
		return -1;
	}

	bool isTerminal = isatty(STDIN_FILENO) != 0;
	if (isTerminal) {
		fprintf(stderr, "Now type your message.\n"
			"Type '.' alone on a line to end your text and send it.\n");
	}

	BString body;
	char line[32768] = "";

	// Read each line and collect the body text until we get an end of text
	// marker.  That's a single dot "." on a line typed in by the user,
	// or end of file when reading a file.
	do {
		if (fgets(line, sizeof(line), stdin) == NULL) {
			// End of file or an error happened, just send collected body text.
			break;
		}

		if (isTerminal && strcmp(line, ".\n") == 0)
			break;

		body.Append(line);
	} while (true);

	if (verbose)
		fprintf(stdout, "\nBody:\n%s\n", body.String());

	if (verbose)
		fprintf(stderr, "Sending E-mail...\n");
	fflush(stdout);

	BMailMessage mail;
	mail.AddHeaderField(B_MAIL_TO, to.String());
	mail.AddHeaderField(B_MAIL_CC, cc);
	mail.AddHeaderField(B_MAIL_BCC, bcc);
	mail.AddHeaderField(B_MAIL_SUBJECT, subject);
	mail.AddContent(body.String(), body.Length());
	status_t result = mail.Send();

	if (result == B_OK) {
		if (verbose)
			fprintf(stderr, "Message was sent successfully.\n");
		return 0;
//.........这里部分代码省略.........
开发者ID:AmirAbrams,项目名称:haiku,代码行数:101,代码来源:mail.cpp

示例11: BAlert

void
PackageView::AttachedToWindow()
{
	status_t ret = fInfo.InitCheck();
	if (ret != B_OK && ret != B_NO_INIT) {
		BAlert* warning = new BAlert("parsing_failed",
				B_TRANSLATE("The package file is not readable.\nOne of the "
				"possible reasons for this might be that the requested file "
				"is not a valid BeOS .pkg package."), B_TRANSLATE("OK"),
				NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
		warning->SetFlags(warning->Flags() | B_CLOSE_ON_ESCAPE);
		warning->Go();

		Window()->PostMessage(B_QUIT_REQUESTED);
		return;
	}

	// Set the window title
	BWindow* parent = Window();
	BString title;
	BString name = fInfo.GetName();
	if (name.CountChars() == 0) {
		title = B_TRANSLATE("Package installer");
	} else {
		title = B_TRANSLATE("Install %name%");
		title.ReplaceAll("%name%", name);
	}
	parent->SetTitle(title.String());
	fBeginButton->SetTarget(this);

	fOpenPanel->SetTarget(BMessenger(this));
	fInstallTypes->SetTargetForItems(this);

	if (ret != B_OK)
		return;

	// If the package is valid, we can set up the default group and all
	// other things. If not, then the application will close just after
	// attaching the view to the window
	_InstallTypeChanged(0);

	fStatusWindow = new PackageStatus(B_TRANSLATE("Installation progress"),
		NULL, NULL, this);

	// Show the splash screen, if present
	BMallocIO* image = fInfo.GetSplashScreen();
	if (image != NULL) {
		PackageImageViewer* imageViewer = new PackageImageViewer(image);
		imageViewer->Go();
	}

	// Show the disclaimer/info text popup, if present
	BString disclaimer = fInfo.GetDisclaimer();
	if (disclaimer.Length() != 0) {
		PackageTextViewer* text = new PackageTextViewer(
			disclaimer.String());
		int32 selection = text->Go();
		// The user didn't accept our disclaimer, this means we cannot
		// continue.
		if (selection == 0)
			parent->Quit();
	}
}
开发者ID:looncraz,项目名称:haiku,代码行数:63,代码来源:PackageView.cpp

示例12: format

float
TruncFileSizeBase(BString* outString, int64 value, const View* view,
	float width)
{
	// ToDo: If slow, replace float divisions with shifts
	//       if fast enough, try fitting more decimal places.

	// ToDo: Update string_for_size() in libshared to be able to
	//       handle this case.

	BString buffer;

	// format file size value
	if (value == kUnknownSize) {
		*outString = "-";
		return view->StringWidth("-");
	} else if (value < kKBSize) {
		static BStringFormat format(B_TRANSLATE(
			"{0, plural, one{# byte} other{# bytes}}"));
		format.Format(buffer, value);
		if (view->StringWidth(buffer.String()) > width)
			buffer.SetToFormat(B_TRANSLATE("%Ld B"), value);
	} else {
		const char* suffix;
		float doubleValue;
		if (value >= kTBSize) {
			suffix = B_TRANSLATE("TiB");
			doubleValue = (double)value / kTBSize;
		} else if (value >= kGBSize) {
			suffix = B_TRANSLATE("GiB");
			doubleValue = (double)value / kGBSize;
		} else if (value >= kMBSize) {
			suffix = B_TRANSLATE("MiB");
			doubleValue = (double)value / kMBSize;
		} else {
			ASSERT(value >= kKBSize);
			suffix = B_TRANSLATE("KiB");
			doubleValue = (double)value / kKBSize;
		}

		for (int32 index = 0; ; index++) {
			if (kSizeFormats[index] == 0)
				break;

			buffer.SetToFormat(kSizeFormats[index], doubleValue, suffix);
			// strip off an insignificant zero so we don't get readings
			// such as 1.00
			char* period = 0;
			for (char* tmp = const_cast<char*>(buffer.String()); *tmp != '\0';
					tmp++) {
				if (*tmp == '.')
					period = tmp;
			}
			if (period && period[1] && period[2] == '0')
				// move the rest of the string over the insignificant zero
				for (char* tmp = &period[2]; *tmp; tmp++)
					*tmp = tmp[1];

			float resultWidth = view->StringWidth(buffer);
			if (resultWidth <= width) {
				*outString = buffer.String();
				return resultWidth;
			}
		}
	}

	return TruncStringBase(outString, buffer.String(), buffer.Length(), view,
		width, (uint32)B_TRUNCATE_END);
}
开发者ID:looncraz,项目名称:haiku,代码行数:69,代码来源:WidgetAttributeText.cpp

示例13: builder

void
BJson::_Parse(BMessage& message, BString& JSON)
{
	BMessageBuilder builder(message);
	int32 pos = 0;
	int32 length = JSON.Length();
	
	/* Locals used by the parser. */
	// Keeps track of the hierarchy (e.g. "{[{{") that has
	// been read in. Allows the parser to verify that openbraces
	// match up to closebraces and so on and so forth.
	BString hierarchy("");
	// Stores the key that was just read by the string parser,
	// in the case that we are parsing a map.
	BString key("");
	
	// TODO: Check builder return codes and throw exception, or
	// change builder implementation/interface to throw exceptions
	// instead of returning errors.
	// TODO: Elimitate more duplicated code, for example by moving
	// more code into _ParseConstant().
	
	while (pos < length) {
		switch (JSON[pos]) {
		case '{':
			hierarchy += "{";
			
			if (hierarchy != "{") {
				if (builder.What() == JSON_TYPE_ARRAY)
					builder.PushObject(builder.CountNames());
				else {
					builder.PushObject(key.String());
					key = "";
				}
			}

			builder.SetWhat(JSON_TYPE_MAP);
			break;

		case '}':
			if (hierarchy.EndsWith("{") && hierarchy.Length() != 1) {
				hierarchy.Truncate(hierarchy.Length() - 1);
				builder.PopObject();
			} else if (hierarchy.Length() == 1)
				return; // End of the JSON data
			else
				throw ParseException(pos, "Unmatched closebrace }");

            break;

		case '[':
			hierarchy += "[";
			
			if (builder.What() == JSON_TYPE_ARRAY)
				builder.PushObject(builder.CountNames());
			else {
				builder.PushObject(key.String());
				key = "";
			}

			builder.SetWhat(JSON_TYPE_ARRAY);
			break;

		case ']':
			if (hierarchy.EndsWith("[")) {
				hierarchy.Truncate(hierarchy.Length() - 1);
				builder.PopObject();
			} else {
				BString error("Unmatched closebrace ] hierarchy: ");
				error << hierarchy;
				throw ParseException(pos, error);
			}

			break;

		case 't':
		{
			if (builder.What() != JSON_TYPE_ARRAY && key.Length() == 0) {
				throw ParseException(pos,
					"'true' cannot be a key, it can only be a value");
			}
			
			if (_ParseConstant(JSON, pos, "true")) {
				if (builder.What() == JSON_TYPE_ARRAY)
					key.SetToFormat("%" B_PRIu32, builder.CountNames());
				builder.AddBool(key.String(), true);
				key = "";
			} else
				throw ParseException(pos, "Unexpected 't'");

			break;
		}

		case 'f':
		{
			if (builder.What() != JSON_TYPE_ARRAY && key.Length() == 0) {
				throw ParseException(pos,
					"'false' cannot be a key, it can only be a value");
			}
			
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例14: if

void
BUrl::SetAuthority(const BString& authority)
{
	fAuthority = authority;

	fHasPort = false;
	fHasUserName = false;
	fHasPassword = false;

	// An empty authority is still an authority, making it possible to have
	// URLs such as file:///path/to/file.
	// TODO however, there is no way to unset the authority once it is set...
	// We may want to take a const char* parameter and allow NULL.
	fHasHost = true;

	if (fAuthority.IsEmpty())
		return;

	int32 userInfoEnd = fAuthority.FindFirst('@');

	// URL contains userinfo field
	if (userInfoEnd != -1) {
		BString userInfo;
		fAuthority.CopyInto(userInfo, 0, userInfoEnd);

		int16 colonDelimiter = userInfo.FindFirst(':', 0);

		if (colonDelimiter == 0) {
			SetPassword(userInfo);
		} else if (colonDelimiter != -1) {
			userInfo.CopyInto(fUser, 0, colonDelimiter);
			userInfo.CopyInto(fPassword, colonDelimiter + 1,
				userInfo.Length() - colonDelimiter);
			SetUserName(fUser);
			SetPassword(fPassword);
		} else {
			SetUserName(fUser);
		}
	}


	// Extract the host part
	int16 hostEnd = fAuthority.FindFirst(':', userInfoEnd);
	userInfoEnd++;

	if (hostEnd < 0) {
		// no ':' found, the host extends to the end of the URL
		hostEnd = fAuthority.Length() + 1;
	}

	// The host is likely to be present if an authority is
	// defined, but in some weird cases, it's not.
	if (hostEnd != userInfoEnd) {
		fAuthority.CopyInto(fHost, userInfoEnd, hostEnd - userInfoEnd);
		SetHost(fHost);
	}

	// Extract the port part
	fPort = 0;
	if (fAuthority.ByteAt(hostEnd) == ':') {
		hostEnd++;
		int16 portEnd = fAuthority.Length();

		BString portString;
		fAuthority.CopyInto(portString, hostEnd, portEnd - hostEnd);
		fPort = atoi(portString.String());

		//  Even if the port is invalid, the URL is considered to
		// have a port.
		fHasPort = portString.Length() > 0;
	}
}
开发者ID:,项目名称:,代码行数:72,代码来源:

示例15: if

_EXPORT void
extract_address_name(BString &header)
{
	BString name;
	const char *start = header.String();
	const char *stop = start + strlen (start);

	// Find a string S in the header (email foo) that matches:
	//   Old style name in brackets: [email protected] (S)
	//   New style quotes: "S" <[email protected]>
	//   New style no quotes if nothing else found: S <[email protected]>
	//   If nothing else found then use the whole thing: S

	for (int i = 0; i <= 3; i++) {
		// Set p1 to the first letter in the name and p2 to just past the last
		// letter in the name.  p2 stays NULL if a name wasn't found in this
		// pass.
		const char *p1 = NULL, *p2 = NULL;

		switch (i) {
			case 0: // [email protected] (S)
				if ((p1 = strchr(start,'(')) != NULL) {
					p1++; // Advance to first letter in the name.
					size_t nest = 1; // Handle nested brackets.
					for (p2 = p1; p2 < stop; ++p2)
					{
						if (*p2 == ')')
							--nest;
						else if (*p2 == '(')
							++nest;
						if (nest <= 0)
							break;
					}
					if (nest != 0)
						p2 = NULL; // False alarm, no terminating bracket.
				}
				break;
			case 1: // "S" <[email protected]>
				if ((p1 = strchr(start, '\"')) != NULL)
					p2 = strchr(++p1, '\"');
				break;
			case 2: // S <[email protected]>
				p1 = start;
				if (name.Length() == 0)
					p2 = strchr(start, '<');
				break;
			case 3: // S
				p1 = start;
				if (name.Length() == 0)
					p2 = stop;
				break;
		}

		// Remove leading and trailing space-like characters and save the
		// result if it is longer than any other likely names found.
		if (p2 != NULL) {
			while (p1 < p2 && (isspace (*p1)))
				++p1;

			while (p1 < p2 && (isspace (p2[-1])))
				--p2;

			int newLength = p2 - p1;
			if (name.Length() < newLength)
				name.SetTo(p1, newLength);
		}
	}

	int32 lessIndex = name.FindFirst('<');
	int32 greaterIndex = name.FindLast('>');

	if (lessIndex == 0) {
		// Have an address of the form <address> and nothing else, so remove
		// the greater and less than signs, if any.
		if (greaterIndex > 0)
			name.Remove(greaterIndex, 1);
		name.Remove(lessIndex, 1);
	} else if (lessIndex > 0 && lessIndex < greaterIndex) {
		// Yahoo stupidly inserts the e-mail address into the name string, so
		// this bit of code fixes: "Joe <[email protected]>" <[email protected]>
		name.Remove(lessIndex, greaterIndex - lessIndex + 1);
	}

	trim_white_space(name);
	header = name;
}
开发者ID:HaikuArchives,项目名称:BeMailDaemon,代码行数:86,代码来源:mail_util.cpp


注:本文中的BString::Length方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。