将一个单词分隔成多个部分(如:->'search'和'ed') [英] Seperate a word into parts ( searced -> 'search' and 'ed' )

查看:92
本文介绍了将一个单词分隔成多个部分(如:->'search'和'ed')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮助我将单词分成几部分吗?例如单词搜索".
我只想在字符串str1中分隔搜索",而将"ed"的另一部分分隔在另一个字符串str2中.我认为我可以在string.h库中使用 strcmp 函数,但是我不知道如何继续解决该问题..

Anyone can help me to split a word into parts? For example the word ''searched'' .
I just want to seperate ''search'' in a string str1 and the other part ''ed'' should be splitted in another string str2 . I think that I can use strcmp function in the library of string.h but I dont know how I should continue to solve the problem..

int main()
{
        // Asked by Sabri Mevis at Gebze Institute of Technology

	char str[20];
	int i=0 , j =0 ;
	int length ;

	cout << "Write a word to be seperated : " ;
	cin >> str ;

	length = strlenFunk(str) ;

	if(strcmp(str, "true") ==0)
		cout << "You are on the right way.\n";

        // Here has not been written
	

	return 0 ;
}

int strlenFunk(const char *str)
{
       const char *chars;

       for (chars = str; *chars; ++chars) ;
       
       return (chars - str);
}

推荐答案

请使用strstr查找子字符串的出现.

http://www.cplusplus.com/reference/clibrary/cstring/strstr/ [ ^ ]

要拆分第二部分,您可以寻找指向第一个子字符串末尾的指针

Please use strstr to find occurance of a sub string.

http://www.cplusplus.com/reference/clibrary/cstring/strstr/[^]

To split the second part, you can seek the pointer to the end of the first sub string

char buff[200];
char part1[200];
char part2[200];

int nPart1Len = strlen("search");
int nPart2Len = strlen(buff) - nPart1Len;
strcpy( buff, "searched" );

if(strstr( buff, "search" )) // Check occurance of first string.
{
    memcpy( part1, buff, nPart1Len); //
    memcpy( part2, buff + strlen( "search" ), nPart2Len );

    part1[nPart1Len] = 0; // Set NULL at end of string.
    part2[nPart2Len] = 0; // Set NULL at end of string.
}


这篇关于将一个单词分隔成多个部分(如:->'search'和'ed')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆