如何找到字符串中的单词而不是子字符串

如何解决如何找到字符串中的单词而不是子字符串

有什么功能可以找到字符串中的确切单词?

char *str = "My birthday is 32.32.2133";
char *new = strstr(str,"day");

因此,在(新)中,我在(str)中的“ d”符号上有了一个指针。但是我需要一个指针,而不是子字符串,而是一个字符串中的单词。因此,在这种情况下,我需要在此处使用NULL指针。 有什么功能可以找到字符串中的确切单词?

所以,如果我有

char *str = "My birthday is 32.32.2133";
char *new = func(str,"birthday");

new将指向b符号,

如果我有

char *str = "My birthday is 32.32.2133";
char *new = func(str,"day");

new将指向NULL

解决方法

有什么功能可以找到字符串中的确切单词?

不,没有函数可以这样做。

您必须编写自己的代码。这可以通过许多不同的方式来完成。这是一种方法(带有一些伪代码)。

1:使用strstr查看您搜索的词是否存在。

pm = strstr(str,word);
if (pm == NULL) return NULL;

如果存在:

2:检查搜索词是否实际上是在字符串中开始一个新词。这意味着strstr返回的位置之前必须有一个空格,或者strstr返回的位置必须与该字符串的开头相同。

if (pm == str) ....  // Fine,start of string

else if (*(pm-1) == ' ') ...  // Fine,space just before the word

else ...  // Bad,not a complete word

3:检查您的搜索词实际上是否在字符串中以词结尾。这意味着strstr返回的位置之后必须紧跟一个空格加上搜索词的大小或{{1}返回的位置 } ,搜索词的大小必须与字符串的末尾相同。

strstr
,

为了确定一个字符串中要搜索的单词是否作为一个完整单词存在,而不是该字符串中另一个单词的子字符串的一部分,您只需要找到该子字符串(无论是否整个单词)然后检查前后的字符是否为[A-Za-z0-9](例如isalnum()-根据需要调整测试)。

如果子字符串之前或之后的字符是字母字符或数字,则您的搜索词在字符串中不以全字形式存在。

如果,另一方面,如果您找到子字符串之前(如果有)的字符,而子字符串之后(如果有)的字符是标点符号的空格,那么您可以考虑将单词整体字符串中的单词。

您可以执行以下操作:仅检查搜索项的长度,在字符串中找到搜索子字符串,然后使用指针算术(或数组索引)隔离子字符串之前和之后的字符(确保测试是否搜索词也从字符串的开头或结尾开始。

一个简单的功能可能是:

const char *findword (const char *s,const char *w)
{
    size_t len = strlen (w);                /* get length of word */
    char *sp = strstr (s,w);               /* get start-pointer to word in string */
    
    if (!sp)                                /* if start-pointer NULL - not found */
        return NULL;
    
    if (sp > s && isalnum (*(sp-1)))        /* if not 1st char and char before sp */
        return NULL;                        /* is [A-Za-z0-9],not a whole word */
    
    if (sp[len] && isalnum(sp[len]))        /* if end not nul-terminating char,and */
        return NULL;                        /* and char after w is [A-Za-z0-9],not
                                               a whole word */
    
    return sp;                              /* return pointer to whole word */
}

(注意:如果您尝试同时使用strtok()strsep()都修改搜索字符串,那么必须确保它是可变的)

如果成功,该函数将返回一个指向整个字符串中整个单词匹配的开头的指针,否则返回NULL。您可以调整搜索范围,以限制单词两端都认为有效的字符。

一个简短的程序,使用该函数,将要搜索的句子作为第一个参数,将要搜索的词作为第二个参数(或者如果没有,则使用"my cat likes hotdogs""dog"作为默认值,或者仅使用给出句子),您可以这样做:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

const char *findword (const char *s,not
                                               a whole word */
    
    return sp;                              /* return pointer to whole word */
}

int main (int argc,char **argv) {
    
    char *text = argc > 1 ? argv[1] : "my cat likes hotdogs",*word = argc > 2 ? argv[2] : "dog";
        
    printf ("text : %s\nword : %s\n%s\n",text,word,findword (text,word) ? "FOUND" : "NOT FOUND");
}

(上面的程序仅使用return来确定是在成功找到字符串中的整个单词,还是在失败时返回"FOUND"时输出"NOT FOUND"

使用/输出示例

"dog"作为整个单词查找的默认情况:

$ ./bin/findwholeword
text : my cat likes hotdogs
word : dog
NOT FOUND

寻找整个词"cat"

$ ./bin/findwholeword "my cat likes hotdogs" "cat"
text : my cat likes hotdogs
word : cat
FOUND

寻找整个词"like"

$ ./bin/findwholeword "my cat likes hotdogs" "like"
text : my cat likes hotdogs
word : like
NOT FOUND

寻找整个词"likes"

$ ./bin/findwholeword "my cat likes hotdogs" "likes"
text : my cat likes hotdogs
word : likes
FOUND

让我知道您是否还有其他问题。

,

这是解决如何在字符串中查找单词的解决方案。详细信息作为注释添加到下面的代码中:

#include <stdio.h>
#include <string.h>
  
int main()
{
    char s[1000],w[1000];  
    int n,a[1000],i,j,k=0,l,found=0,t=0;
 
    printf("Enter  the string : ");
    scanf ("%[^\n]%*c",s);
    printf("Enter word to be searched: ");
    scanf ("%[^\n]%*c",w);
    
    // Checking how many words are there in the given string and store those lengths of words in an array
    for(i=0;s[i];i++)
    {
        if(s[i]==' ')
        {
            a[k++]=i;
        }
    }
    
    a[k++]=i;
    
    j=0;
    
    for(i=0;i<k;i++)
    {
        n=a[i]-j; // Finding word length from the number of words in the given string
        
        if(n==strlen(w)) // Checking whether the length of a stored word is equal to the length of the searched word or not,if then check all the characters
        {
            t=0;
            
            for(l=0;w[l];l++)
            {
                if(s[l+j]==w[l])
                {
                    t++;
                }
            }
            
            if(t==strlen(w))
            {
                found++;
                printf("word '%s'  is occurred at location=%d \n",w,j);
 
            }
        }
    
        j=a[i]+1; // Update the length of previous stored word
    }
    
    if(found==0)
    {
        printf("Word '%s' is not available in the given string.",w);
    }

    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res